[Abstract] There are two ways to call an object directly in iOS, one of which is Nsinvocation, which describes iOS Nsinvocation usage and provides simple sample code for reference.
There are two ways to call an object directly in iOS:
One is performselector:withobject;
Another is nsinvocation.
The first approach is simple and can be done with simple calls. But for >2 parameters or the handling of return values, there is a need to do some extra work to get it done. So in this case, we can use nsinvocation to do these relatively complex operations.
Main.h
View Row Code
| 1 |
#import <Foundation/Foundation.h> |
| 2 |
#import "MyClass.h" |
| 3 |
|
| 4 |
int Main (int argc, const Char * argv[]) |
| 5 |
{ |
| 6 |
|
| 7 |
nsautoreleasepool * Pool = [[nsautoreleasepool alloc] init]; |
| 8 |
|
| 9 |
MyClass *myclass = [[MyClass alloc] init]; |
| 10 |
nsstring *mystring = @"My string"; |
| 11 |
|
| 12 |
//Normal call |
| 13 |
nsstring *normalinvokestring = [MyClass appendmystring:mystring]; |
| 14 |
NSLog (@"The normal Invoke string is:%@", normalinvokestring); |
| 15 |
|
| 16 |
//nsinvocation Call |
| 17 |
SEL myselector = @selector (appendmystring:); |
| 18 |
nsmethodsignature * sig = [[MyClass class] |
| 19 |
Instancemethodsignatureforselector:myselector]; |
| 20 |
|
| 21st |
nsinvocation * myinvocation = [nsinvocation invocationwithmethodsignature:sig]; |
| 22 |
[myinvocation settarget:myclass]; |
| 23 |
[myinvocation setselector:myselector]; |
| 24 |
|
| 25 |
[myinvocation setargument: &mystring atindex: 2]; |
| 26 |
|
| 27 |
nsstring * result = nil; |
| 28 |
[myinvocation retainarguments]; |
| 29 |
[Myinvocation invoke]; |
| 30 |
[myinvocation getreturnvalue: &result]; |
| 31 |
NSLog (@"The Nsinvocation invoke string is:%@", result); |
| 32 |
|
| 33 |
[MyClass release]; |
| 34 |
|
| 35 |
[Pool drain]; |
| 36 |
return 0; |
| 37 |
} |
MyClass.h
View Row Code
| 1 |
#import <Foundation/Foundation.h> |
| 2 |
|
| 3 |
|
| 4 |
@interface MyClass : nsobject { |
| 5 |
} |
| 6 |
|
| 7 |
-(nsstring *)appendmystring: (nsstring *) string; |
| 8 |
|
| 9 |
@end |
Myclass.m
View Row Code
| 1 |
#import "MyClass.h" |
| 2 |
|
| 3 |
|
| 4 |
@implementation MyClass |
| 5 |
|
| 6 |
-(ID)init |
| 7 |
{ |
| 8 |
Self = [Super init]; |
| 9 |
if (self) { |
| 10 |
//initialization code here. |
| 11 |
} |
| 12 |
|
| 13 |
return self; |
| 14 |
} |
| 15 |
|
| 16 |
-(nsstring *) appendmystring: (nsstring *) string |
| 17 |
{ |
| 18 |
nsstring *mstring = [nsstring stringWithFormat:@"%@ after Append method", string< c11>]; |
| 19 |
|
| 20 |
return mstring; |
| 21st |
} |
| 22 |
|
| 23 |
-(void)dealloc |
| 24 |
{ |
| 25 |
[Super dealloc]; |
| 26 |
} |
| 27 |
|
| 28 |
@end |
Here is a description of [myinvocation setargument: &mystring atindex:2]; Why is index starting from 2 because: 0 12 parameters have been occupied by target and selector.
Introduction to IOS nsinvocation usage