问题
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