Reputation: 2550
A day or so ago I posted this question: Confused about enumeration... How do I change the objects that during enumeration?
I learned that I can call methods on an object during enumeration, but if I assign using the "=" operator then it creates a new object (not what I want).
The linked question shows how to use setString on an array of NSString objects... but now my question is for custom objects
Here's what I want to do
for (Car * car in self.carsArray)
{
if (car.name == nil){
car = [self getrandomCar];
}
}
However, the "=" operator isn't going to work for me... is there some type of method I can use like this?
[car setObject:[self getrandomCar];
Thanks!
Upvotes: 0
Views: 950
Reputation: 850
First of all, if you want to change the object pointed to in the array, you have to change the array, not the pointer the fast enumeration gives you. Second, you can't change the array during fast enumeration (well, you can, but it will blow up in your face). I suggest you make a copy of the array before enumeration and then modify that during enumeration, throwing out the original array after enumeration is done. For example:
tempArray = [self.carsArray mutableCopy];
for (Car * car in self.carsArray)
{
if (car.name == nil){
[tempArray replaceObjectAtIndex:[self.carsArray indexOfObject:car] withObject:[self getrandomCar]];
}
}
[self.carsArray release];
self.carsArray = [tempArray copy];
[tempArray release];
tempArray = nil;
It's not as pretty as fast enumeration would have you believe, but it's what has to be done if you want to change the array while enumerating through it.
Upvotes: 8