Selector is another feature which supports ObjectiveC. A Selector is same as function pointers in C. So Using selector, we will get the reference of the method, later we will use that reference for calling the method. A SEL is a special type which holds a pointer to the symbolic name of a method.
@selector is a directive to get the pointer for the method. After getting the reference, using below two methods we can do the operations.
@selector is a directive to get the pointer for the method. After getting the reference, using below two methods we can do the operations.
- respondsToSelector : This used to check whether the method definition is available or not. It does not look for the declaration of the method, it just checks in implementation file for the method definition.
- performSelector : This is used to call the method.
//both are same , any one is fine SEL selectorName= @selector(methodName); SEL selectorName = NSSelectorFromString(@”methodName");Using Selectors to Call Methods: Below is the example for the usage of the selector and its methods.
//This is in .h file @interface selectorDemo : NSObject -(void) display; -(void) output; @end //below is in .m file @implementation selectorDemo -(void) display { NSLog(@"this is display function"); } -(void) output { NSLog(@"this is output function"); } @end //this is in main.m int main(int argc, const char * argv[]) { selectorDemo *obj = [[selectorDemo alloc] init]; // This selector declaration for display method SEL selDisplay = @selector(display); //checking whether method definition is available or not if([obj respondsToSelector:selDisplay]) { //calling method [obj performSelector:selDisplay]; } //another syntax for the selector declaration SEL selOutput = NSSelectorFromString(@"output"); //calling method [obj performSelector:selOutput]; return 0; }
No comments:
Post a Comment