Call instance method with objc_msgSend

Posted by user772349 on Stack Overflow See other posts from Stack Overflow or by user772349
Published on 2012-09-19T03:31:31Z Indexed on 2012/09/19 3:37 UTC
Read the original article Hit count: 164

I'm trying to use the objc_msgSend method to call some method dynamically. Say I want call some method in Class B from Class A and there are two methods in class B like:

- (void) instanceTestWithStr1:(NSString *)str1 str2:(NSString *)str1;
+ (void) methodTestWithStr1:(NSString *)str1 str2:(NSString *)str1;

And I can call the class method like this in Class A successfully:

objc_msgSend(objc_getClass("ClassB"), sel_registerName("methodTestWithStr1:str2:"), @"111", @"222");

And I can call the instance method like this in Class A successfully as well:

objc_msgSend([[objc_getClass("ClassB") alloc] init], sel_registerName("instanceTestWithStr1:str2:"), @"111", @"222");

But the thing is to get a instance of Class B I have to call "initWithXXXXX:XXXXXX:XXXXXX" instead of "init" so that to pass some necessary parameters to class B to do the init stuff. So I stored a instance of ClassB in class A as variable: self.classBInstance = [[ClassB alloc] initWithXXXXX:XXXXXX:XXXXXX];

And then I call the method like this (successfully):

The problem is, I want to call a method by simply applying the classname and the method sel like "ClassName" and "SEL" and then call it dynamically:

  1. If it's a class method. then call it like: objc_msgSend(objc_getClass("ClassName"), sel_registerName("SEL"));

  2. If it's a instance method, find the existing class instance variable in the calling class then: objc_msgSend([self.classInstance, sel_registerName("SEL"));

So I want to know if there is any way to:

  1. Check if a class has a given method (I found "responseToSelector" will be the one)

  2. Check if a given method in class method or instance method (maybe can use responseToSelector as well)

  3. Check if a class has a instance variable of a given class So I can call a instance method like: objc_msgSend(objc_getClassInstance(self, "ClassB"), sel_registerName("SEL"));

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about cocoa