0

OOP の経験はありますが、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 例外が発生することです。

誰でも私を助けてもらえますか?

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

4

1 に答える 1

4

あなたが作成treeObstaclesした

treeObstacles = [NSMutableArray arrayWithObjects: nil];

自動解放されたオブジェクトを返しますが、それを保持していないため、すぐに解放されます

あなたはそれを呼び出すことによってそれを保持する必要があり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
    }
}

そうしないと、オブジェクトが正しく初期化されません

于 2012-04-22T08:36:37.107 に答える