2011-06-07 66 views

回答

7

在Objective-C中,就像在C中一樣,&是「address-of operator」,它返回它的參數地址。要了解更多信息,我建議您閱讀The C Book中的this short chapter

這裏的運營商是如何使用的例子,以獲得更好的主意:

#include <stdio.h> 

// define a function that takes a pointer to an integer as argument 
void change_value_of_int(int* int_to_change) { 
    // change the value to which the argument points 
    *int_to_change = 5; 
} 

int main() { 
    // create a stack variable 
    int test_int = 10; 

    // pass the address of test_int to the function defined earlier 
    change_value_of_int(&test_int); 

    // now the value of test_int is 5 
    printf("%d\n", test_int); 

    return 0; 
} 

注意,change_value_of_int()函數期望第一個參數是一個指針爲int,而不是一個int,所以你不能用change_value_of_int(test_int)來調用它。您必須發送test_int變量的地址,而不是變量本身(因爲如果您發送變量的副本,則無法更改它)。

NSError*示例相同。 jsonParser預計地址NSError*,而不是一個NSError*,因此該方法被定義爲:

- (id)objectWithString:(NSString*)jsonrep error:(NSError**)error; 

the header file看一看,在the implementation,看看它是如何使用的。您的error*error = error參數指向的值的值)的值將成爲[errorTrace lastObject]的返回值。

+0

謝謝,這完全解釋了我的。我感謝你的時間。 – 2011-06-08 15:04:37

5

這是在C,C++和Objective-C中找到的運算符的地址。

在你的例子中,&error產生一個NSError **(也就是指向指針的指針)。

這在C語言中是很常見的(通過擴展名Objective-C):通過引用模擬指針,這意味着您必須傳遞要修改的對象的地址(在這種情況下,另一個指針)到一個函數。

0

&是地址運算符。 真正的快速教訓,Objective-C中的所有對象都是指針,這使得事情變得簡單,因爲你知道所有事物的冷漠程度,id是一種特殊情況,它指向任何對象,而不指定類。

指向指針的指針在返回錯誤時最常使用,該錯誤作爲參數傳遞給方法。

-(void)doSomething:(NSError**)err 
{ 
    //we have an error, return it. 
    *err = [NSError errorWithDomain:@"custom Domain" code:42 userInfo:nil]; 

} 

然後使用該方法以:

NSError * err = nil; 
    [self doSomething:&err]; 
    if(err) 
    { 
     NSLog(@"we have an error in domain: %@",[err domain]); 
    } 

,其輸出:

我們在域一個錯誤:定製 域

這是當特別有用你正在返回一些東西,因爲你只能返回一個值C.這是非常普遍的是香草C和C++,但在Objective-C中沒有那麼多用處。

+2

在Cocoa中,您應該總是在嘗試使用錯誤對象之前檢查直接返回值。切勿使用if(err)'來確定方法是否失敗。 – 2011-06-07 21:39:14

+0

是的,你是對的,那將是一個好習慣。 – 2011-06-07 21:40:51