SELECTORS
In Objective-C, a selector refers to the name used to select a method to execute for an object. It is used to identify a method. You have seen the use of a selector in some of the chapters in this book. Here is one of them:
//---create a Button view--- CGRect frame = CGRectMake(10, 50, 300, 50); UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = frame; [button setTitle:@“Click Me, Please!” forState:UIControlStateNormal]; button.backgroundColor = [UIColor clearColor]; [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
The preceding code shows that you are dynamically creating a UIButton object. In order to handle the event (for example, the Touch Up Inside event) raised by the button, you need to call the addTarget:action:forControlEvents: method of the UIButton class:
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
The action: parameter takes an argument of type SEL (selector). In the preceding code, you pass in the name of the method that you have defined — buttonClicked: — which is defined within the class:
-(IBAction) buttonClicked: (id) sender { //... }
Alternatively, you can create an object of type SEL and then instantiate it by using the NSSelectorFromString function (which takes a string containing the method name):
NSString *nameOfMethod = @“buttonClicked:”; SEL methodName = NSSelectorFromString(nameOfMethod);
Get Beginning iOS 5 Application Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.