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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With