使用委托数组时出错

时间:2011-12-27 17:32:01

标签: iphone ios ios5 sigabrt exc-bad-access

我试图通过使用我的app委托中的“Player”对象数组初始化来创建不同类中的“Player”对象。这段代码与ios 4.3一起工作(现在仍然如此),但崩溃了(SIGABRT或exec_bad_access)和ios 5.0。

我已导入了app delegate。

以下是失败的代码:

PlaybookAppDelegate *delegate = (PlaybookAppDelegate *)
[[UIApplication sharedApplication] delegate];
Player *thisPlayer = [delegate.players objectAtIndex:index.row];

以下是我的AppDelegate中的声明:

@interface PlaybookAppDelegate : NSObject <UIApplicationDelegate>
{
    NSMutableArray *players;   
}

@property (nonatomic, retain) NSMutableArray *players; 

这是定义“index”

的方法
-(id)initWithIndexPath:(NSIndexPath *)indexPath{
if (self == [super init] ) {
    index = indexPath;
}
return self;
}   

2 个答案:

答案 0 :(得分:3)

indexPath是一个对象,而不是一个struct,所以如果你不取得它的所有权,它将被解除分配。您应该能够解决此问题:

-(id)initWithIndexPath:(NSIndexPath *)indexPath
{
  if( (self == [super init]) ) {
    index = [indexPath retain]; // need to take ownership of this
  }
  return self;
}

- (void)dealloc
{
  // include all your regular -dealloc code
  [index release];
  [super dealloc];
}

此外,由于存在这些类型的内存问题,您在iOS 5中看到错误绝对是巧合。它在iOS 4下也无法运行,您很幸运。

答案 1 :(得分:1)

您是否在任何地方初始化了Players阵列?如果不这样做,那将导致访问不良。