Skip to Content
Beginning iOS 5 Application Development
book

Beginning iOS 5 Application Development

by Wei-Meng Lee
January 2012
Beginner content levelBeginner
655 pages
16h 35m
English
Wrox
Content preview from Beginning iOS 5 Application Development

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);
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering iOS 12 Programming - Third Edition

Mastering iOS 12 Programming - Third Edition

Donny Wals
What Successful Project Managers Do

What Successful Project Managers Do

W. Scott Cameron, Jeffrey S. Russell, Edward J. Hoffman, Alexander Laufer

Publisher Resources

ISBN: 9781118144251Purchase book