Reputation: 3340
I have a code that is pretty much the same the only thing that changes is the property the code "works" on for example
-(void) removeItemsBelowPrice:(NSInteger)p_minimumPrice andAbove:(NSInteger)p_maximumPrice
{
for( int itemIdx = self.itemsList.count-1; itemIdx >= 0 ; itemIdx--)
{
if(((BasicItem*)self.itemsList[itemIdx]).price < p_minimumPrice ||
((BasicItem*)self.itemsList[itemIdx]).price > p_maximumPrice)
{
[self.itemsList removeObjectAtIndex:itemIdx];
}
}
}
so for the property amountInStorage, I'd have the same function duplicated and change the property from price to amountInStorage, i was wondering if there is a way to write a generic function that can receive the property to work on, if possible can this property be of different types
thanks.
Upvotes: 1
Views: 112
Reputation: 9311
Yes, you can do it with NSPredicate:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(YOUR_PROPERTY > LOWER_LIMIT) AND (YOUR_PROPERTY < UPPER_LIMIT)"];
[yourArray filteredArrayUsingPredicate:predicate]
Let's see some untested example code:
-(NSArray*)filterArray:(NSArray*)array byProperty:(NSString*)property lowerLimit:(double)lowerLimit upperLimit:(double)upperLimit{
return [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(%@ >= %g) AND (%@ <= %g)",property,lowerLimit,property,upperLimit]]];
}
Upvotes: 4
Reputation: 122391
You are modifying the collection class while enumerating it, which you cannot do (this issue occurs in many languages, not just Objective-C).
Use this technique instead, which first finds all the objects to remove then removes them:
NSIndexSet *indexes = [self.itemList indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
BasicItem *basicItem = (BasicItem *)obj;
return basicItem.price < p_minimumPrice || basicItem.price > p_maximumPrice;
}];
[self.itemList removeObjectsAtIndexes:indexes];
Upvotes: 2