我想向NSMutableArray添加选择器。但是由于它们是不透明的类型,并且没有对象,所以这不会起作用,对吧?有没有我可以使用的包装器对象?或者我必须创建我自己的?
发布于 2009-05-30 00:57:25
可以将选择器的NSString名称存储在数组中,并使用
SEL mySelector = NSSelectorFromString([selectorArray objectAtIndex:0]);从存储的字符串生成选择器。
此外,您还可以使用以下内容将选择器打包为NSInvocation
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:mySelector]];
[invocation setTarget:self];
[invocation setSelector:mySelector];
[invocation setArgument:&arg atIndex:2];
[invocation retainArguments];然后可以将这个NSInvocation对象存储在数组中,并在以后调用。
发布于 2009-05-29 22:46:00
您可以将其封装在NSValue实例中,如下所示:
SEL mySelector = @selector(performSomething:);
NSValue *value = [NSValue value:&mySelector withObjCType:@encode(SEL)];然后为您的NSMutableArray实例增加价值。
发布于 2011-12-27 05:57:26
NSValue valueWithPointer / pointerValue同样工作得很好。
你只需要知道你不能序列化数组(也就是把它写到一个文件中),如果你想这样做的话,使用NSStringFromSelector方法。
这些都是将选择器放入NSValue对象的有效方法:
id selWrapper1 = [NSValue valueWithPointer:_cmd];
id selWrapper2 = [NSValue valueWithPointer:@selector(viewDidLoad)];
id selWrapper3 = [NSValue valueWithPointer:@selector(setObject:forKey:)];
NSString *myProperty = @"frame";
NSString *propertySetter = [NSString stringWithFormat:@"set%@%@:",
[[myProperty substringToIndex:1]uppercaseString],
[myProperty substringFromIndex:1]];
id selWrapper4 = [NSValue valueWithPointer:NSSelectorFromString(propertySetter)];
NSArray *array = [NSArray arrayWithObjects:
selWrapper1,
selWrapper2,
selWrapper3,
selWrapper4, nil];
SEL theCmd1 = [[array objectAtIndex:0] pointerValue];
SEL theCmd2 = [[array objectAtIndex:1] pointerValue];
SEL theCmd3 = [[array objectAtIndex:2] pointerValue];
SEL theCmd4 = [[array objectAtIndex:3] pointerValue];https://stackoverflow.com/questions/928449
复制相似问题