In Objective-C, there are at least two ways to get (or create? Hence the question) a selector: @selector(foo:bar:), or NSSelectorFromString(@"foo:bar:"). But what is the lifetime of a selector?
Since selectors know (at least) their name, they are unlikely to be copiable values of a fixed size that can be shuffled around the program. This means that someone needs to allocate and possibly deallocate them. Most objects from the Cocoa framework have retain-release semantics, which make their ownership explicit and relatively easy to track. However, I see no clear concept of ownership for selectors.
I expect that selectors obtained with the first syntax live as globals for the whole life of the program (like literal strings), but what about the other? If I create/get a selector with NSSelectorFromString(@"foo:bar:"), will it be valid for the whole life of my program too?
It’s “get”, not “create”. Both of those simply retrieve the selector, which is created and owned by the runtime system. The
SEL‘s lifetime is therefore effectively immortal.If you wanted to create a selector yourself, you would need to use the runtime function
sel_registerName(). This function is used byNSSelectorFromString()if you pass it a name which is as yet unknown to the runtime.