Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of Cocoa @selector usage

Tags:

I'm new to Cocoa/Cocoa Touch, and working through a development book. I've come across situations where the @selector() operator is used. I'm a bit lost on how and when the @selector() operator should be used. Can someone provide a short and sweet explanation and example of why it's used and what benefit it gives the developer?

By the way, here is sample code taken from Apple's iPhone development site that uses @selector()

if ([elementName isEqualToString:@"entry"]) {      parsedEarthquakesCounter++;      // An entry in the RSS feed represents an earthquake, so create an instance of it.     self.currentEarthquakeObject = [[Earthquake alloc] init];     // Add the new Earthquake object to the application's array of earthquakes.     [(id)[[UIApplication sharedApplication] delegate]             performSelectorOnMainThread:@selector(addToEarthquakeList:)             withObject:self.currentEarthquakeObject waitUntilDone:YES];     return; } 
like image 702
mshafrir Avatar asked Feb 12 '09 20:02

mshafrir


People also ask

What is selector method?

A selector is an identifier which represents the name of a method. It is not related to any specific class or method, and can be used to describe a method of any class, whether it is a class or instance method. Simply, a selector is like a key in a dictionary.

What is a selector OBJC?

In Objective-C, selector has two meanings. It can be used to refer simply to the name of a method when it's used in a source-code message to an object. It also, though, refers to the unique identifier that replaces the name when the source code is compiled. Compiled selectors are of type SEL .

What is a selector Xcode?

A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled.


1 Answers

The selector operator provides a way to refer to a method provided by an object, somewhat similar to a function pointer in C. It is useful because it allows you to decouple the process of calling methods on an object. For example one piece of code could provide a method, and another piece of code could apply that method to a given set of objects.

Examples:

Test to see if an object implements a certain method:

[object respondsToSelector:@selector(methodName)] 

Store a method to later call on an object;

SEL method = @selector(methodName); [object performSelector:method]; 

Call a method on a different thread (useful for GUI work).

[object performSelectorOnMainThread:@selector(methodName)] 
like image 142
Andrew Grant Avatar answered Oct 18 '22 08:10

Andrew Grant