Wednesday, May 25, 2016

Objective-C SEL and @selector

SEL is a data type like int, NSString, NSArray etc.... Which holds kind of method signature. @selector gives the kind of method signature to us.

Let's discuss in detail with an example. 

- (void)doSomething1{

   - (void)doSomething2:(NSString*)val{

   - (void)doSomething3:(NSString*)val1 withAnotherObject:(NSString*)val2 {

  SEL myMethod1 = @selector(doSomething1);
    SEL myMethod2 = @selector(doSomething2:);
    SEL myMethod3 = @selector(doSomething3:withAnotherObject:);

These are useful,

#1 When we need to do introspection before calling methods.

    if([self respondsToSelector: myMethod1])
        // Same as [myObj doSomething1];
        [self performSelector: myMethod1];   
    if([self respondsToSelector: myMethod2])

        // Same as [myObj doSomething2:@"val"];
        [self performSelector:myMethod2 withObject:@"val"];   
     if([self respondsToSelector: myMethod3])

        // [myObj doSomething3:@"val1" withAnotherObject:@"val2"];
        [self performSelector:myMethod3 withObject:@"val1" withObject:@"val2"];  

Calling, [self performSelector:myMethod2], will give EXC_BAD_ACCESS as we are supposed to pass a parameter which we didn't.


#2 When we need to run a simple background operation

[self performSelectorInBackground:myMethod2 withObject:@"iOSSolves"];

#3 When we need to run something on Main thread while we are in a background thread

[self performSelectorOnMainThread:myMethod2 withObject:@"iOSSolves" 

#4 When we need to run something after a particular delay

[self performSelector:myMethod2 withObject:@"iOSSolves" afterDelay:2.0];

performSelector works for methods having max 2 parameters. If a method is having more than 2 parameters, It doesn't work. We need to go for NSInvocation for that situation.


Hope this post is useful. Feel free to comment in case of any queries.