Is there a wrapper object for SEL?

I want to add selectors to NSMutableArray. But since they are opaque types and no objects, this will not work, right? Can I use a wrapper object? Or do I need to create my own?

+4
source share
3 answers

You can store the NSString name of the selector in an array and use

SEL mySelector = NSSelectorFromString([selectorArray objectAtIndex:0]); 

to generate a selector from a stored string.

Alternatively, you can pack the selector as an NSInvocation using something like

 NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:mySelector]]; [invocation setTarget:self]; [invocation setSelector:mySelector]; [invocation setArgument:&arg atIndex:2]; [invocation retainArguments]; 

This NSInvocation object can then be stored in an array and called later.

+5
source

You can wrap it in an instance of NSValue as follows:

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

and then add the value to your instance of NSMutableArray .

+9
source

The value of NSValueWithPointer / pointerValue works equally well.

you just need to know that you cannot serialize the array (i.e. write it to a file), if you want to do this, use the NSStringFromSelector approach.

These are all valid ways to place a selector in an NSValue object:

  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]; 
+2
source

All Articles