Objective C: Two implicit parameters passed to every method called by an object

495 views Asked by At

What are the two implicit parameters passed to every method by an object in Objective-c? Is it _cmd and id?

1

There are 1 answers

0
HeshamElmandoh On BEST ANSWER

That is a good question, the short answer is: yes, two parameters are being implicitly passed. self of type id, and _cmd of type SEL.

to better understand it, here is what happens behind the method call.

@interface Item:NSObject
-(void)dummyMethod;
@end
@implementation Item
-(void)dummyMethod{
     NSLog(@"dummyPrint");
}
@end

a normal method call would be like:

Item* objectOne = [[Item alloc]init;
[objectOne dummyMethod];

that call gets translated/complied to:

objc_msgSend(objectOne,@selector(dummyMethod)); //since the dummy method takes no parameters and returns void

to try it/use it your self. 1. #import<objc/message.h 2. cast the objc_msgSend method to an appropriate function pointer type before being used, like that.

void (*objc_msgSendPointer)(id self, SEL _cmd) = (void*)objc_msgSend;
objc_msgSendPointer(one, @selector(dummyMethod)); 

here is the function declaration

 id objc_msgSend(id self, SEL op, ...);

take a look at this documentation for further info.. objc_msgSend. take a look also at this topic using objc_msgSend to call a Objective C function with named arguments for more info regarding other methods, specially Ken's answer.

I hope that was helpful!