【问题标题】:NSMutableArray's count method throws an exception when called in expressionNSMutableArray 的 count 方法在表达式中调用时抛出异常
【发布时间】:2011-11-22 08:47:17
【问题描述】:
 if ([diamonds count] == 0) {
    [self toggleWinLevel];
}

当 diamonds 是 NSMutableArray 并且 toggleWinLevel 是实例方法时,如果我运行此应用程序,它会在此行崩溃并显示 EXC_BAD_ACCESS:

 if ([diamonds count] == 0) {

这肯定与我的数组有关,因为即使我将 int 或 NSUInteger 或 NSNumber 分配给数组的计数,这种情况也会继续发生。我的 NSMutableArray 已分配并初始化。问题是什么?

更新 1:

我已经在这个方法中分配并初始化了它,它确实被调用了,我有 NSLog,它确实在控制台中登录以进行证明:

    -(void)setUpObjects {

NSLog(@"Setting Up Objects"); // This is printed in my console

[levelNumberLabel setHidden:YES];
diamonds = [[NSMutableArray alloc] init];
rocks = [[NSMutableArray alloc] init];

if (levelNumber < 3) {

    diamonds = [NSMutableArray arrayWithObjects:@"1", nil];

} else if (levelNumber > 2 <= 4) {

    diamonds = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil];

} else if (levelNumber > 4 <= 6) {

    diamonds = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", nil];

} else if (levelNumber > 6 <= 10) {

    diamonds = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", nil];

} else if (levelNumber > 10) {

    diamonds = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", nil];
}

if ([diamonds count] > 1 <= 2) {

    rocks = [NSMutableArray arrayWithObjects:@"1", @"2", nil];                 

} else if ([diamonds count] > 2 <= 5) {

    rocks = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil];

} else if ([diamonds count] > 5) {

    rocks = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", nil];
}

[self drawObjects];
}

BTW diamonds(数组)是一个实例变量

【问题讨论】:

  • “我的 NSMutableArray 已分配和初始化” - 你能说明你在哪里做的吗?因为这似乎是这里的问题。请包括属性声明和初始设置代码。
  • BTW diamonds(数组)是一个实例变量
  • if (levelNumber &gt; 2 &lt;= 4) 这应该有效吗?我手头没有一个 ObjectiveC 编译器,但我猜这会转化为 if ((levelNumber &gt; 2) &lt;= 4),这总是正确的。

标签: objective-c xcode nsmutablearray nsarray


【解决方案1】:

你是第一次打电话:

diamonds = [[NSMutableArray alloc] init];

但后来调用,例如:

diamonds = [NSMutableArray arrayWithObjects:@"1", nil];

第二次调用将分配给diamonds 一个自动释放的对象,您需要保留该对象。

您的代码中存在不一致之处,即第一次调用时您有一个保留对象,而不是第二次调用中的自动释放对象。

【讨论】:

  • ...更不用说内存泄漏了。
【解决方案2】:

您很可能过度释放了 diamonds 数组,换句话说,数组对象已被释放,您正在尝试为其调用方法。使用 NSZombieEnabled=YES 参数或 Instruments with Zombies。

【讨论】:

  • 考虑到我只发布过一次并且在 dealloc 方法中,我并没有过度释放数组
  • 事实上,你没有保留它,这会让你得到与访问随机内存相同的结果。
【解决方案3】:

要么按照 ThomasW 的建议执行并保留新数组(但这会泄漏您的原始实例),要么只是将项目添加到数组中而不是创建新数组:

diamonds = [NSMutableArray arrayWithObjects:@"1", nil];

应该阅读

[diamonds addObjectsFromArray:[NSArray arrayWithObjects:@"1", nil]];

这会将对象添加到现有数组中,而不是创建新数组。

您已经使用 alloc/init 创建了 diamonds 数组,您正在将其重新创建为 if 语句中的自动释放变量。

这同样适用于您的 rocks 数组。

【讨论】:

  • 谢谢,这很有帮助
猜你喜欢
  • 2020-04-30
  • 2014-10-19
  • 2017-05-31
  • 2011-10-22
  • 2012-11-22
  • 2016-07-10
  • 2023-03-24
  • 2010-12-15
  • 1970-01-01
相关资源
最近更新 更多