Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the -self method in NSObject-conformant classes?

That's it. Why would anyone want (at least as a public API) a method such as that? Is there any practical use for it?

like image 962
Matoe Avatar asked Dec 15 '12 20:12

Matoe


2 Answers

The self method is useful for Key-Value Coding (KVC).

With KVC, you can treat an object somewhat like a dictionary. You can access a property of the object using a string containing the name of the property, like this: [view valueForKey:@"superview"]. You walk down a chain of properties using a string containing a key path, like this: [view valueForKeyPath:@"superview.superview.center"].

Since NSObject has a self method, you can use self as the key or key path: [view valueForKey:@"self"]. So if you're constructing your key paths programmatically, or reading them from a file, using "self" as a key may allow you to avoid writing a special case.

You can also use self in predicates, like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self beginswith \"foo\""];
NSArray *filteredArray = [arrayOfStrings filteredArrayWithPredicate:predicate];

I don't know whether NSPredicate actually uses the self method (perhaps via KVC) in this case. It's certainly possible.

like image 183
rob mayoff Avatar answered Sep 27 '22 23:09

rob mayoff


I'm not sure why "self" was added originally, but one thing it did come in handy for was protecting interior pointers to objects. Apple's official recommendation was to insert a [foo self] call after you're done with the interior pointer; the method call does nothing functionally but ensures the compiler keeps foo around until then.

like image 44
Wade Tregaskis Avatar answered Sep 27 '22 23:09

Wade Tregaskis