IOS: CHCSVParser & NSPredicate?

I am currently trying to use CHCSVParser to parse CSV files containing more than 1500 records and 8 lines. I was able to parse the file and I am getting NSArray from NSArrays from NSStrings.

For example, here is what I get:

Loading CSV from: (
        (
        Last,
        First,
        Middle,
        Nickname,
        Gender,
        City,
        Age,
        Email
    ),
        (
        Doe,
        John,
        Awesome,
        "JD",
        M,
        "San Francisco",
        "20",
        "john@john.doe"
    ),

How can I sort this in a Person object and filter it using NSPredicate, for example, MattT Thompson does here .

This is how I initialize the parser:

//Prepare Roster
    NSString *pathToFile = [[NSBundle mainBundle] pathForResource:@"myFile" ofType: @"csv"];
    NSArray *myFile = [NSArray arrayWithContentsOfCSVFile:pathToFile options:CHCSVParserOptionsSanitizesFields];
    NSLog(@"Loading CSV from: %@", myFile);

Here's what Matt does in the article I linked that I would like to do with my code:

NSArray *firstNames = @[ @"Alice", @"Bob", @"Charlie", @"Quentin" ];
NSArray *lastNames = @[ @"Smith", @"Jones", @"Smith", @"Alberts" ];
NSArray *ages = @[ @24, @27, @33, @31 ];

NSMutableArray *people = [NSMutableArray array];
[firstNames enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    Person *person = [[Person alloc] init];
    person.firstName = firstNames[idx];
    person.lastName = lastNames[idx];
    person.age = ages[idx];
    [people addObject:person];
}];
+3
source share
1 answer

First determine the appropriate class Person:

@interface Person : NSObject
@property(copy, nonatomic) NSString *firstName;
@property(copy, nonatomic) NSString *lastName;
// ...
@property(nonatomic) int age;
// ...
@end

Person, myFile. row - "-" :

NSMutableArray *people = [NSMutableArray array];
[myFile enumerateObjectsUsingBlock:^(NSArray *row, NSUInteger idx, BOOL *stop) {
    if (row > 0) { // Skip row # 0 (the header)
       Person *person = [[Person alloc] init];
       person.lastName = row[0];
       person.firstName = row[1];
       // ...
       person.age = [row[6] intValue];
       // ...
       [people addObject:person];
   }
}];

, :

NSPredicate *smithPredicate = [NSPredicate predicateWithFormat:@"lastName = %@", @"Smith"];
NSArray *filtered = [people filteredArrayUsingPredicate:smithPredicate];
+1

All Articles