2012-04-22 41 views
0

儘管OOP經驗豐富,但我是Objective-C的絕對新手。我有以下代碼:Objective-C對象數組

// header files have been imported before this statement... 
CCSprite *treeObstacle; 
NSMutableArray *treeObstacles; 

@implementation HelloWorldLayer { 
} 

-(id) init 
{ 
    // create and initialize our seeker sprite, and add it to this layer 
    treeObstacles = [NSMutableArray arrayWithObjects: nil];   
    for (int i=0; i<5; i++) { 
     treeObstacle = [CCSprite spriteWithFile: @"Icon.png"]; 
     treeObstacle.position = ccp(450-i*20, 100+i*20); 
     [self addChild:treeObstacle]; 
     [treeObstacles addObject: treeObstacle]; 
    } 
    NSLog (@"Number of elements in array = %i", [treeObstacles count]); 
    return self; 
} 

- (void) mymethod:(int)i { 
    NSLog (@"Number of elements in array = %i", [treeObstacles count]); 
} 

@end 

第一個NSLog()語句返回「數組中的元素數= 5」。問題是(儘管treeObstacles是一個文件範圍變量)調用方法「mymethod」時,我會得到一個EXC_BAD_ACCESS異常。

任何人都可以幫我嗎?

非常感謝 基督教

+0

你怎麼稱呼它?這是很重要的 – 2012-04-22 08:33:40

+0

@ xlc0212的回答是點上但是如果您是Objective-C的新手,那麼爲什麼不通過構建啓用ARC的項目來啓動並運行它。您稍後可以瞭解內存管理? – deanWombourne 2012-04-22 08:43:53

+0

是的,你是對的。實際上,我在作弊:該方法的名稱不是mymethod(),而是由Cocos2D Framework使用的nextFrame()。 奇怪的是,如果我在init方法的某個地方調用[self nextFrame:1],它會按預期工作... – itsame69 2012-04-22 08:54:17

回答

4

treeObstacles = [NSMutableArray arrayWithObjects: nil]; 

它會返回一個自動釋放的對象創建treeObstacles,而你沒有留住它,所以它會很快被釋放

你有通過致電retain對其進行保留

[treeObstacles retain]; 

簡單的通過

treeObstacles = [[NSMutableArray alloc] init]; 

創建它,你需要記住釋放它的時候像

- (void)dealloc { 
    [treeObstacles release]; 
    [super dealloc]; 
} 

做,你需要在Objective-C閱讀更多有關管理 https://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/MemoryManagement.html

或使用ARC,因此不必擔心保留/釋放 http://developer.apple.com/library/ios/#releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html


另外一個問題,你需要調用[super init]init方法

- (id)init { 
    self = [super init]; 
    if (self) { 
     // your initialize code 
    } 
} 

否則你的對象將不能正確初始化

+0

非常感謝你的幫助!這正是我正在尋找並解決問題!豎起大拇指 – itsame69 2012-04-22 09:01:22

+0

...並感謝有用的鏈接! – itsame69 2012-04-22 09:10:46