2012-04-22 71 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