[英]NSInvocation returning nil
有誰知道如何將NSInvocation
的參數設置為nil
? 我正在嘗試使用OCMock
並且希望此期望返回nil。 問題是,調用該方法時,我需要做其他事情,如您在示例中所看到的,這就是為什么我不這樣做andReturn:nil
我想做這個:
[[[myObject stub] andDo:^(NSInvocation *inv) {
[inv setReturnValue:Nil];
[inv invoke];
[self notify:kXCTUnitWaitStatusSuccess]; //Code that I need to execute
}] myMethod:OCMOCK_ANY];
但是我得到一個錯誤:
*** Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[NSInvocation setArgument:atIndex:]:
NULL address argument'
有人知道是否還有另一種方法可以將其設置為nil嗎? 還是不可能?
首先,您的代碼沒有任何意義。 您應該在調用之前設置調用的參數,所調用的方法將讀取您提供給它的參數,並設置返回值,然后可以在調用之后讀取返回值。 對您而言,在調用返回值之前先對其進行設置是沒有意義的,因為根據定義,“返回值”是調用后“返回”的事物,並且將在調用結束時進行設置,並覆蓋您的所有內容設置之前。
為了解決您遇到的錯誤,對於所有getArgument
, setArgument
, getReturnValue
和setReturnValue
函數,您需要將指針傳遞到要讀取或寫入值的緩沖區。 這是因為參數和返回值可以是各種大小的各種C類型,因此無法直接傳遞它。 在這種情況下,似乎要讀取/寫入的值是一個對象指針,因此您需要創建一個對象指針類型的變量,設置為所需的值(如果要設置的話),然后將指向此變量的指針傳遞給getArgument
/ setArgument
/ getReturnValue
/ setReturnValue
。
@newacct指出了這一點,他是完全正確的。 您不能在實際調用之前設置調用的返回值。 為了使調用結果為“ nil
”,我所做的就是修改調用的參數,以便調用將要調用的代碼生成nil
。 讓我用一個例子解釋一下:
- (void)viewDidLoad {
NSString *arg = @"HelloWorld";
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(isHelloWorld:)]];
[invocation setSelector:@selector(isHelloWorld:)];
[invocation setTarget:self];
[invocation setArgument:&arg atIndex:2];
NSString *result1 = nil;
[invocation invoke];
[invocation getReturnValue:&result1];
NSString *result2 = [self resultOfModifiedInvocation:invocation];
NSLog(@"result 1: %@",result1);
NSLog(@"result 2: %@",result2);
}
- (NSString *) resultOfModifiedInvocation:(NSInvocation *) invocation {
NSString *aString = @"NoWorld";
[invocation setArgument:&aString atIndex:2];
[invocation invoke];
[invocation getReturnValue:&aString];
return aString;
}
- (NSString *) isHelloWorld:(NSString *) aString{
if([aString isEqualToString:@"HelloWorld"])
return aString;
else
return nil;
}
方法isHelloWorld:
應該返回@"HelloWorld"
因為我們在調用中發送的內容是正確的。 實際上,由於參數尚未修改,因此在您第一次調用調用時實際上會發生這種情況。 另一方面,通過調用resultOfModifiedInvocation:
調用的參數將被修改,然后調用的結果將有所不同。
這是示例的輸出:
> result 1: HelloWorld
> result 2: (null)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.