问题
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.
Problem:
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];
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.
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
Edit: Food is defined and allocated here:
@interface MainLayer
{
NSMutableArray *_food;
}
In the class init
method
_food = [[NSMutableArray alloc] init];
回答1:
You are overreleasing here:
for (Food *food in _food) {
if(!food.removeable){
[foodToKeep addObject:food];
// [food release]; <--- REMOVE THIS
}
}
And here
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.
回答2:
You are releasing Food
objects you don't own. Have a look at Objective-C Memory Management Rules.
In fact, in the line:
for (Food *food in _food) {
You don't own the object food, so you should not release it in the first loop, nor in the second loop.
回答3:
You are releasing food
after you added it to the array, but the release doesn't balance a retain
call so when you reach [_food removeAllObjects]
presumably all Food objects get deallocated there and hence it crashes when you try to access it again later.
来源:https://stackoverflow.com/questions/9352226/nsmutablearray-access-issue