iOS:CHCSVParser& NSPredicate?

时间:2014-02-10 06:29:00

标签: ios objective-c csv nsarray nspredicate

我目前正在尝试使用CHCSVParser来解析包含超过1500个条目和8行的CSV文件。我已经成功地解析了文件,我得到的是NSArrays NSSrings的NSArray。

例如,这是我得到的:

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

我如何将其排序为Person对象并使用NSPredicate过滤它,就像Mattt Thompson here一样。

以下是我初始化解析器的方法:

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

以下是Mattt在我链接的文章中所做的事情,我想用我的代码做:

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

1 个答案:

答案 0 :(得分:1)

首先,定义一个合适的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];