简体   繁体   中英

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 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.

如果可变数组中的每个对象都具有manufacturer属性,则谓词应为

 [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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM