What's this about SEL and @selector?

Saturday, September 20 2003 @ 10:34 PM UTC

Contributed by: witness

SEL is the data type for storing a shorthand notation of a method's name. @selector() is a pseudo-function you can use to get a SEL from a method name. Together, they let you do the equivalent of calling a function via a function pointer, but for a method of an object.

Depending on the class of your object, ObjC has to call a different method for the same method name (e.g. NSString's longValue or NSNumber's longValue). To allow that, ObjC uses a SEL to quickly find functions with the same name, which is faster than comparing the actual function name strings. To get such a SEL, you use code like the following:

SEL mySel = @selector(methodNameParam:andParam:);
(for a method declared as -(void)methodNameParam: (int)a andParam: (int)b;) To call a method using a selector, use one of NSObject's performSelector: methods, which pretty much any class inherits from in the end (though maybe indirectly).