Call instance method with objc_msgSend
- by user772349
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:
If it's a class method. then call it like:
objc_msgSend(objc_getClass("ClassName"), sel_registerName("SEL"));
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:
Check if a class has a given method (I found "responseToSelector" will be the one)
Check if a given method in class method or instance method (maybe can use responseToSelector as well)
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"));