在iOS中可以直接調用某個對象的訊息方式有2中 一種是performSelector:withObject: 再一種就是NSInvocation 第一種方式比較簡單,能完成簡單的調用。但是對於>2個的參數或者有傳回值的處理,那就需要做些額外工作才能搞定。那麼在這種情況下,我們就可以使用NSInvocation來進行這些相對複雜的操作 |
main.h [html]
view plaincopy
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. //普通調用 13. NSString *normalInvokeString = [myClass appendMyString:myString];
14. NSLog(@"The normal invoke string is: %@", normalInvokeString);
15. 16. //NSInvocation調用 17. SEL mySelector = @selector(appendMyString:);
18. NSMethodSignature * sig = [[myClass class]
19. instanceMethodSignatureForSelector: mySelector];
20. 21. 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
[html]
view plaincopy
1. #import <Foundation/Foundation.h> 2. 3. 4. @interface MyClass : NSObject {
|