问题
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?
回答1:
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.
回答2:
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.
回答3:
I think it's to do with the ObjC runtime.
objc_msgSend(autoreleasePool, sel_registerName("drain"));
BOOL AppDel_didFinishLaunching(struct AppDel *self, SEL _cmd, void *application, void *options)
The first argument is self. I think it has something to do with that. In all honesty though as it would end up as:
id self(struct id *self, SEL _cmd) {
return self;
}
....It made more sense before I started writing this response.
来源:https://stackoverflow.com/questions/13895789/what-is-the-purpose-of-the-self-method-in-nsobject-conformant-classes