4

我想将选择器添加到 NSMutableArray。但是由于它们是不透明的类型并且没有对象,所以这是行不通的,对吧?有我可以使用的包装器对象吗?还是我必须自己创建?

4

3 回答 3

9

您可以将其包装在一个NSValue实例中,如下所示:

SEL mySelector = @selector(performSomething:);
NSValue *value = [NSValue value:&mySelector withObjCType:@encode(SEL)];

然后为您的NSMutableArray实例增加价值。

于 2009-05-29T22:46:00.107 回答
5

您可以将选择器的 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-30T00:57:24.773 回答
2

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];
于 2011-12-26T21:57:25.967 回答