读书人

ios NSInvocation简略使用

发布时间: 2012-07-20 10:38:30 作者: rapoo

ios NSInvocation简单使用

在ios直接调用某个对象的消息是方法有两种:

一:performselector:withObject:

二:invocation

?

第一种方式比较简单,能完成简单的调用。但是对于>2个的参数或者有返回值的处理,那就需要做些额外工作才能搞定。那么在这种情况下,我们就可以使用NSInvocation来进行这些相对复杂的操作

?

NSInvocation可以处理参数、返回值。会java的人都知道凡是操作,其实NSInvocation就相当于反射操作。

?

?

?

- (NSString *) myMethod:(NSString *)param1 withParam2:(NSNumber *)param2{NSString *result = @"Objective-C";NSLog(@"Param 1 = %@", param1);NSLog(@"Param 2 = %@", param2);return(result);}- (void) invokeMyMethodDynamically {SEL selector = @selector(myMethod:withParam2:);NSMethodSignature *methodSignature = [[self class] instanceMethodSignatureForSelector:selector];NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];[invocation setTarget:self];[invocation setSelector:selector];NSString *returnValue = nil;NSString *argument1 = @"First Parameter";NSNumber *argument2 = [NSNumber numberWithInt:102];[invocation setArgument:&argument1 atIndex:2];[invocation setArgument:&argument2 atIndex:3];[invocation retainArguments];[invocation invoke];[invocation getReturnValue:&returnValue];NSLog(@"Return Value = %@", returnValue);} 

?

?

To do this, you need to follow these steps:
1. Form a SEL value using the name of the method and its parameter names (as
explained in Recipe 1.7).
2. Form a method signature of type NSMethodSignature out of your SEL value.
3. Form an invocation of type NSInvocation out of your method signature.
4. Tell the invocation what object you are targeting.
5. Tell the invocation what selector in that object you want to invoke.
6. Assign any arguments, one by one, to the invocation.
7. Invoke the method using the invocation object and demand a return value (if any).

1 楼 ak478288 2012-02-29 兄弟,你上半部分的文章为什么和我的原创文章一模一样呢?如果是引用,请加原文链接,谢谢

读书人网 >操作系统

热点推荐