description of message that triggered a method invocation

一个人想着一个人 提交于 2019-12-13 03:11:53

问题


Does the objective-c runtime allow getting a description of the message that triggered a method invocation - from within that method itself?

For example, if I have a method called: -(Foobar)doMyStuff; . . is it possible from within that method to get something like:

//This would return @"doMyStuff"
NSString* selectorName = [foobar nameOfMessageThatTriggeredMyInvocation]; 

回答1:


Yes. Every method has its selector passed in as a hidden argument. It's the second argument, after self, and it is named _cmd:

NSString * selectorName = NSStringFromSelector(_cmd);

That's why objc_msgSend(id self, SEL _cmd, ...) looks the way it does, and why, if you construct an NSInvocation, you start at index 2 when setting your arguments.




回答2:


Josh's answer is totally correct, I might also add that this is useful for logging.

Class myClass = object_getClass(self);
NSLog(@"I am in %c[%@ %s]", class_isMetaClass(myClass) ? '+' : '-', myClass, sel_getName(_cmd));

"I am in -[AppDelegate application:didFinishLaunchingWithOptions:]"

Although it's probably easier to use -

NSLog(@"So pretty %s", __PRETTY_FUNCTION__);

"So pretty -[AppDelegate application:didFinishLaunchingWithOptions:]"

Which gets inserted at compile time, and is certainly faster. If you do any dynamic method resolution though using _cmd is extremely helpful.



来源:https://stackoverflow.com/questions/14421494/description-of-message-that-triggered-a-method-invocation

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