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

余生长醉 提交于 2019-11-30 12:18:49

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!