iOS:CHCSVParser和NSPredicate是什么?

3
我目前正在尝试使用CHCSVParser解析包含1500多个条目和8行的CSV文件。我已成功地解析了文件,得到了一个NSStrings的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在这里所做的那样。

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

//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个回答

1
首先,定义一个适当的 Person 类:
@interface Person : NSObject
@property(copy, nonatomic) NSString *firstName;
@property(copy, nonatomic) NSString *lastName;
// ...
@property(nonatomic) int age;
// ...
@end

然后,您可以通过枚举 myFile 数组将数据读入 Person 对象的数组中。在块内,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];

感谢您对过程进行解释和简化! - KingPolygon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接