NSMutableArray访问问题 [英] NSMutableArray Access Issue

查看:98
本文介绍了NSMutableArray访问问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我(认为我)知道您在想什么……不是另一个EXC_BAD_ACCESS问题,但是我真的很挣扎,这使我发疯.我在整个网上中搜索了高低,而我所面临的问题似乎与我的内存管理有关.

I (think I) know what you're thinking... not another EXC_BAD_ACCESS question but I'm really struggling and it's driving me crazy. I've searched high and low all over the net and on here and the issue I'm facing seems have something to do with my memory management.

问题:

基本上,我有一个NSMutableArray可以跟踪一些网络食品.由于可以同时添加和取出食物,因此我有一个单独的数组,用于检查要删除的项目并保存需要不需要的项目.然后的想法是清除原始数组( _food )并复制回保存在临时数组( foodToKeep )中的所有项目.这是代码

Basically I have an NSMutableArray that keeps track of some cyber food. Since food can be added and taken away at the same time I have a separate array that checks for items to remove and holds the ones that don't need to be taken out. The idea is to then clear the original array (_food) and copy back all the items saved in the temporary array (foodToKeep). Here's the code

NSMutableArray *foodToKeep = [[NSMutableArray alloc] init];

for (Food *food in _food) {
    if(!food.removeable){
        [foodToKeep addObject:food];
        [food release];
    }
}

if(foodToKeep > 0){
  [_food removeAllObjects];

  for (Food *food in foodToKeep) {
      [_food addObject:food]; // EXC_BAD_ACCESS error here
      [food release];
      }
  }
}

[foodToKeep release];

将食物添加到原始数组时出现错误的访问错误.搜索之后,听起来好像 _food 数组正在某个地方释放,或者以某种方式最终以 nil 结尾.我对_food拥有release的唯一位置是在dealloc方法中,因此我无法理解为什么会发生这种情况.

I get the bad access error when add the food to the original array. After searching around it sounds like the _food array is being released somewhere or somehow ending up as nil. The only place I have a release for _food is in the dealloc method so I can't understand why this is happening.

我对Objective-C还是很陌生(所以,请放轻松!),据我所知,没有泄漏和意外释放会导致这种情况,我认为我需要的是专家的眼光看看我最可能犯下的一个小错误:-P

I'm fairly new to Objective-C (so go easy on me!) but as far as I can tell there are no leaks and no accidental releases that are causing this, I think what I need is an experts eye to see what is most likely a trivial mistake on my part :-P

修改: 食物在这里定义和分配:

Food is defined and allocated here:

    @interface MainLayer
    {
        NSMutableArray *_food;
    }

在类init方法中

    _food = [[NSMutableArray alloc] init];

推荐答案

您在这里过分释放:

for (Food *food in _food) {
    if(!food.removeable){
        [foodToKeep addObject:food];
        // [food release];  <--- REMOVE THIS
    }
}

还有这里

for (Food *food in foodToKeep) {
      [_food addObject:food]; // EXC_BAD_ACCESS error here
      // [food release]; <--- REMOVE THIS
}

删除多余的版本,您应该会没事的.

Remove the extra releases and you should be fine.

这篇关于NSMutableArray访问问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆