19

What's the value of _cmd variable when I access it from C-style function's body?

Is it defined inside Objective-C methods only?

P.S. This question may originate from my non-understanding of what _cmd is. I would greatly appreciate if someone provided me with a good explanation source.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
wh1t3cat1k
  • 3,146
  • 6
  • 32
  • 38

3 Answers3

25

The major use of the _cmd function is to get the method name in which it is called.

The use of the _cmd with some other functions has been written below.

NSLog(@"<%@:%@:%d>", NSStringFromClass([self class]), NSStringFromSelector(_cmd), __LINE__);

Instead of above line you can also use PrettyFunction

NSLog(@"%s", __PRETTY_FUNCTION__); 
21

It's for Objective-C methods only, so you can't access it. The first two parameters passed to all Objective-C methods are self and _cmd, then whatever other arguments the actual method takes. Since neither self nor _cmd are passed to regular C functions, you can't access them.

There's nothing particularly magic about either variable.

cjohnson318
  • 3,154
  • 30
  • 33
Jason Coco
  • 77,985
  • 20
  • 184
  • 180
  • 3
    For reference: [Objective-C methods](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html). Note that any C function that takes an `id` and `SEL` as its first two arguments can be used as a method implementation. Similarly, any method implementation is a C function that takes an `id` and `SEL` as its first two arguments. – outis Dec 18 '10 at 20:08
  • 8
    To be extra clear, `_cmd` is an `SEL` -- the method selector for the Objective-C method. "A method selector is a C string that has been registered (or 'mapped') with the Objective-C runtime." – Ben Flynn Apr 23 '13 at 20:29
0

Please look here for further explanations.

func class_addMethod(_ cls: AnyClass!, 
                   _ name: Selector!, 
                   _ imp: IMP!, 
                   _ types: UnsafePointer<Int8>!) -> Bool

imp:

A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd.
Nike Kov
  • 12,630
  • 8
  • 75
  • 122