我想使用將指針指向NSError對象作爲參數的方法來創建NSInvocation對象。這方面的一個例子是方法 -如何使用將指針指向對象的方法作爲參數來創建NSInvocation對象
- (BOOL)writeToFile:(NSString *)path options:(NSDataWritingOptions)mask error:(NSError **)errorPtr
我undersand,我會爲我設置調用像這樣
NSData *myData = [[NSData alloc] init];
SEL writeToFileSelector = @selector(writeToFile:options:error:);
NSMethodSignature *signature = [NSData instanceMethodSignatureForSelector:writeToFileSelector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:myData];
[invocation setSelector:writeToFileSelector];
NSString *string = [NSString stringWithFormat:@"long cat"];
NSDataWritingOptions *dataOptions;
*dataOptions = NSDataWritingFileProtectionComplete;
[invocation setArgument:&string atIndex:2];
[invocation setArgument:&dataOptions atIndex:3];
對於將writeToFile:選項:錯誤:最後一個參數期望接收的指針而不是一個對象。其結果是執行以下操作不起作用 -
NSError *err = nil;
[invocation setArgument:&err atIndex:4];
這似乎是合乎邏輯的解決方案可能是創建一個指針的指針,但這會導致編譯器警告。我不知道如何正確執行,不會造成內存管理問題。
「但是,既然你沒有告訴它指向任何變量,它指向零。」什麼?不,它沒有定義 – user102008 2012-05-11 18:49:25
「現在你可以傳入errorPointer作爲參數」你不解釋如何傳遞它。 – user102008 2012-05-11 18:50:13
#1在ARC下,未分配的本地指針變量被自動設置爲零。在C或非ARC Obj-C中,你是正確的。 #2傳遞errorPointer作爲第四個參數'[invocation setArgument:&errorPointer atIndex:4]' – edelaney05 2012-05-11 21:22:07