2012-04-22 9 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"を返します。問題は、メソッド "mymethod"を呼び出すときにtreeObstaclesがファイルスコープ変数であるにもかかわらず、EXC_BAD_ACCESS例外が発生することです。

誰でもお手伝いできますか?

どうもありがとう クリスチャン

+0

を初期化しないのだろうか?それはxlc0212の答え@重要 –

+0

だ上のスポットですObjective-Cを初めてお使いになる場合は、ARCを有効にして起動してプロジェクトを構築することから始めましょう。少し後でメモリ管理について知ることができますか? – deanWombourne

+0

はい、あなたは正しいです。実際、私は不正行為をしていました。メソッドの名前は、Cocos2D Frameworkで使用されているmymethod()ではなくnextFrame()です。 initメソッドのどこかで[self nextFrame:1]を呼び出すと、それは期待どおりに動作します。 – itsame69

答えて

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


別の問題は、あなたがあなたのinit方法

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

[super init]を呼び出す必要がありそうでない場合は、あなたのオブジェクトは、あなたがそれを呼び出すにはどうすればよい適切

+0

あなたの親切な助けをありがとう!これはまさに私が探していたものであり、問​​題を解決するものです!上に戻る – itsame69

+0

...と便利なリンクをありがとう! – itsame69

関連する問題