开发者

Filter a NSMutableArray of objects and copy to a new NSArray

I have a NSObject defined with a few properties and to keep this question simple, let's say th开发者_Python百科e 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.


If each object in the mutable array has a manufacturer property then predicate should be

 [NSPredicate predicateWithFormat:@"manufacturer = %@", @"Ford"];


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];
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜