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);

The call to the addTarget:action:forControlEvents: method now looks like this:

[button addTarget:self
           action:methodName
 forControlEvents:UIControlEventTouchUpInside];

image NOTE When naming a selector, be sure to specify the full name of the method. For example, if a method name has one or more parameters, you need to add a “:” in the sector, such as the following:

NSString *nameOfMethod = @“someMethod:withPara1:andPara2:”;

image NOTE Because Objective-C is an extension of C, it is common to see C functions interspersed throughout your Objective-C application. C functions use parentheses () to pass in arguments for parameters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.184.122