2013-02-27 67 views
0

讓我們來想象這樣的情景:訪問目標C數組

Game.h:

@interface Game : CCLayer 
{  
    NSMutableArray* questions; 
} 

@property (nonatomic,retain) NSMutableArray* questions; 


- (void) didLoadFromCCB; 
- (void) pressitem:(id)sender; 

@end 

Game.m

@implementation Game 

@synthesize questions; 

- (void) didLoadFromCCB 
{ 
    NSMutableArray *questions = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithInteger:-1],nil]; 

    NSLog(@"didload %@", questions); 
} 


- (void) pressitem:(id)sender 
{ 
    NSLog(@"pressitem %@",questions); 
} 
@end 

我從didLoadFromCCB但對pressitem得到它的日誌返回null。不應該通過我的所有實現訪問數組嗎?

我知道這個接縫像一個真正的noob問題,但是我來自一個actionscript/php背景,而我只是訂購了一個C和一本Objective C的書,但是當我等待時,我只是想挖一點。

感謝您的時間:)

回答

0

範圍。 NSMutableArray *questions聲明- didLoadFromCCB方法的局部變量。它不設置實例變量(具有較小範圍的變量抑制具有相同名稱但範圍較寬的變量)。簡單地寫

self.questions = [[NSMutableArray alloc] initWithObject:[NSNumber numberWithInteger:-1]]; 

改爲。

+0

如果您不使用ARC,這可能會導致內存泄漏,該屬性會增加保留數+1以及alloc指令。因此,您以保留計數爲2的對象結束,並且您可能只會在dealloc方法中釋放一個對象。 – 2013-02-27 22:32:55

+0

@PaulN我知道。 (你真的以爲我不知道?)但除了我之外,似乎沒有人再使用MRC了。太糟糕了。 – 2013-02-27 22:36:38

+0

謝謝你們倆=)確實self.questions工作,當我點擊它記錄數組,但它後崩潰我的應用程序,在使用它之後,我需要某種dealoc? – 2013-02-27 22:37:10

2

你的questionsdidLoadFromCCB陰影的實例變量的局部聲明。你或許應該只是使該行:

self.questions = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithInteger:-1],nil]; 

那麼你將創建陣列和存儲一個指向它的實例變量,而不是隻建立一個本地指針馬上超出範圍。

+0

爲什麼不設置屬性,如果它被聲明? – 2013-02-27 22:30:14

+0

也可以。甚至可能是首選。我會編輯它。 – 2013-02-27 22:30:44

+0

完美,謝謝。 – 2013-02-27 22:31:38