Reputation: 573
I have a NSObject defined with a few properties and to keep this question simple, let's say the object is called Vehicle and there are three properties: Manufacturer, Model, Year.
I read all vehicles from a database and the result is a NSMutableArray of Vehicle objects.
I am trying to create a new array of vehicles that are filtered by manufacturer where the object = "Ford".
Is the correct approach:
NSPredicate *fordMotorCarsPredicate = [NSPredicate predicateWithFormat:@"ANY Vehicle.Manufacturer = %@", @"Ford"];
fordMotorCarsArray = [listOfVehicles filteredArrayUsingPredicate:fordMotorCarsPredicate];
I know I could filter the list using an SQL query, but I'd like to know whether this can be achieved in Objective-C code.
Any ideas? Cheers, Ross.
Upvotes: 4
Views: 2716
Reputation: 6842
You can use a predicate only if the underlying objects are KVC-compliant for the key you are testing against. But that condition is actually a weak condition. It's enough for example to have a property by that name.
Now you can always filter your array manually:
- (NSMutableArray *) cars:(NSArray *)listOfVehicles builtBuy:(NSString*)manufacturer {
NSMutableArray *resultCars = [[NSMutableArray alloc] init];
for (Car *aCar in listOfVehicles) {
if ([manufacturer isEqualToString:aCar.Manufacturer]) {
[resultCars addObject:aCar];
}
}
return [resultCars autorelease];
}
Upvotes: 1
Reputation: 3494
Ther is an alternative to NSPredicat but i'm not sure it's worth it in your case... sow this is how you sort an array alfabetically,
somearray =[[NSMutableArray alloc] initWithArray:an array];
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"Vehicle" ascending:YES] autorelease];
[somearray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
however if you need a more specific sorting you can add a selector to the sort descriptor that will hold the logic of the sorting like this
NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"Vehicle" ascending:NO selector:@selector(VehicleSortingLogic:)];
I never used it with a selector before but it should work , hope this helps
Upvotes: 0
Reputation: 25281
If each object in the mutable array has a manufacturer
property then predicate should be
[NSPredicate predicateWithFormat:@"manufacturer = %@", @"Ford"];
Upvotes: 2