2009-05-29 40 views
4

我想將選擇器添加到NSMutableArray。但是因爲它們是不透明的類型並且沒有對象,所以這是行不通的,對吧?有我可以使用的包裝對象嗎?或者我必須創建自己的?是否有SEL的包裝對象?

回答

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的對象可以被存儲在數組中和以後調用。

+0

有趣 - 我從來沒有使用NSInvocation的 - 謝謝! – 2009-06-01 23:15:52

9

您可以在NSValue爲例說明如下把它包:

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

再增值到您NSMutableArray實例。

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]; 
相關問題