iOS NSInvocationの使用理解
2966 ワード
iOSでオブジェクトを直接呼び出すメッセージ方式は2種類あります performSelector:withObject: NSInvocation
1つ目の方法は比較的簡単で、簡単な呼び出しを完了することができます.しかし,>2個のパラメータや戻り値のある処理では,処理がかなり面倒である.第2のNSInvocationもメッセージ呼び出しの方法であり、そのパラメータは制限されず、パラメータ、戻り値などの比較的複雑な操作を処理することができる.
1.初期化使用無パラメータ無戻り値 パラメータあり戻り値なし パラメータあり戻り値 2.一般的な方法と属性 NSInvocationその他の一般的なメソッド属性 NSMethodSignatureその他の一般的なメソッド属性
1つ目の方法は比較的簡単で、簡単な呼び出しを完了することができます.しかし,>2個のパラメータや戻り値のある処理では,処理がかなり面倒である.第2のNSInvocationもメッセージ呼び出しの方法であり、そのパラメータは制限されず、パラメータ、戻り値などの比較的複雑な操作を処理することができる.
1.初期化使用
- (void)invocation{
// sig
NSMethodSignature *sign = [[self class] instanceMethodSignatureForSelector:@selector(method)];
// invocation
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sign];
// target
invocation.target = self;
// selector
invocation.selector = @selector(method);
//
[invocation invoke];
}
- (void)method {
NSLog(@"method ");
}
- (void)invocation{
// sig
NSMethodSignature *sign = [[self class] instanceMethodSignatureForSelector:@selector(sendMessage:name:)];
// invocation
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sign];
//
NSString *name = @" ";
NSString *message = @" ";
// 2 , target selector
[invocation setArgument:&name atIndex:2];
[invocation setArgument:&message atIndex:3];
invocation.target = self;
invocation.selector = @selector(sendMessage:name:);
//
[invocation invoke];
}
- (void)sendMessage:(NSString*)message name:(NSString*)name{
NSLog(@"%@ %@",name,message);
}
- (void)invocation{
// sig
NSMethodSignature *sign = [[self class] instanceMethodSignatureForSelector:@selector(sumNumber1:number2:)];
// invocation
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sign];
//
invocation.target = self;
invocation.selector = @selector(sumNumber1:number2:);
NSInteger number1 = 30;
NSInteger number2 = 10;
[invocation setArgument:&number1 atIndex:2];
[invocation setArgument:&number2 atIndex:3];
//
[invocation invoke];
//
NSNumber *sum = nil;
[invocation getReturnValue:&sum];
NSLog(@" ==%zd",[sum integerValue]);
}
- (NSNumber*)sumNumber1:(NSInteger)number1 number2:(NSInteger)number2{
NSInteger sum = number1+number2;
return @(sum);
}
// , target retain
- (void)retainArguments
// , retainArguments , NO, YES
@property (readonly) BOOL argumentsRetained;
//
- (void)setReturnValue:(void *)retLoc;
//
@property (readonly) NSUInteger numberOfArguments;
//
@property (readonly) NSUInteger frameLength;
//
- (BOOL)isOneway;
//
@property (readonly) const char *methodReturnType NS_RETURNS_INNER_POINTER;
//
@property (readonly) NSUInteger methodReturnLength;