1

我正在使用 NSInvocation 进行动态调用:

NSInvocation *lNSInvocation = [NSInvocation invocationWithMethodSignature: [lListener methodSignatureForSelector:lSelector]];
[lNSInvocation setTarget:lListener];
[lNSInvocation setSelector:lSelector];
// Note: Indexes 0 and 1 correspond to the implicit arguments self and _cmd, which are set using setTarget and setSelector.
[lNSInvocation setArgument:object atIndex:2];
[lNSInvocation setArgument:object2 atIndex:3];
[lNSInvocation setArgument:object3 atIndex:4];
[lNSInvocation invoke];

在调试器中,所有三个对象变量都正确指向三个不同的 NSCFString*。调用完成,另一方面,到达了正确的方法。

- (void)login:(NSString*)username password:(NSString*)password host:(NSString*)host

但是,在调试器中,它的参数给出错误:“变量不是 CFString”。更糟; 所有三个变量都指向同一个内存位置。

怎么会这样?

4

1 回答 1

2

如果方法参数是对象,则-setArgument:atIndex:需要一个指向可以从中复制对象的变量的指针。因此,如果您的字符串是:

NSString *object = @"…";
NSString *object2 = @"…";
NSString *object3 = @"…";

那么你应该写:

[lNSInvocation setArgument:&object atIndex:2];
[lNSInvocation setArgument:&object2 atIndex:3];
[lNSInvocation setArgument:&object3 atIndex:4];

(注意每个对象参数之前的与号)

于 2011-02-21T10:30:24.953 回答