2012-03-06 146 views
0
#import <Foundation/Foundation.h> 

typedef struct Node { 
    int offset; 
} Node; 

int main (int argc, const char * argv[]) 
{ 

    @autoreleasepool { 

     NSMutableArray *array = [[NSMutableArray alloc] init]; 
     Node node = {111111}; 
     NSValue *value = [NSValue value:&node withObjCType:@encode(Node)]; 
     [array addObject:value]; 

     NSValue *structValue = [array objectAtIndex:0]; 
     Node *n = (Node *)[structValue pointerValue]; 

     printf("offset: %d", n->offset); 
    } 
    return 0; 
} 

代碼崩潰,在這條線:printf("offset: %d", n->offset);但爲什麼呢?爲什麼這個簡單的代碼會導致EXC_BAD_ACCESS?

+0

如果在printf行之前檢查'n'的內容會發生什麼? – 2012-03-06 14:10:16

+0

我只是無法訪問'n-> offset',但'printf(「%d」,n)'輸出'111111'。但是如果我在'Node'結構中添加另一個字段,'printf(「%d」,n)'只打印第一個字段的值。 – neevek 2012-03-06 14:17:25

回答

3

獲得C值回正確的做法是getValue:

Node n; 
[structValue getValue:&n]; 

pointerValue指針不返回到存儲的值,它讀取內存的指針值,其中Node存儲(如union { Node n; void* pointerValue; })。

+0

謝謝,它工作! – neevek 2012-03-06 14:37:53

2

如果你想添加一個指針和接收一個指針代替NSValue *value = [NSValue valueWithPointer:&node];

相關問題