I am trying to scan through an NSMutableArray and remove all 0’s. (They are wrapped in NSNumber objects). I was trying to just use a for loop to search through, but I come across the issue that once I remove an object, it causes an index out of bounds issue for future iterations. I can’t think of a logical way to easily solve this issue.
My current code is this:
for(int i =0; i < [array count]; i++)
{
if(!abs([[array objectAtIndex: i] floatValue]) > 0.0)
{
[array removeObjectAtIndex: i];
}
}
Is there a way to fix up my loop or use a special method/function to just eliminate all 0s?
I recommend using NSArray’s
filteredArrayUsingPredicate:method with a simple block, like so:The logic in the block is simple, any float which is non-zero is truthy, and thus passes the predicate.