iOS:CHCSVParser&;预测?
我目前正试图使用CHCSVParser解析一个包含1500多个条目和8行的CSV文件。我成功地解析了整个文件,得到的是NSArray的NSArray字符串 例如,我得到的是:iOS:CHCSVParser&;预测?,ios,objective-c,csv,nsarray,nspredicate,Ios,Objective C,Csv,Nsarray,Nspredicate,我目前正试图使用CHCSVParser解析一个包含1500多个条目和8行的CSV文件。我成功地解析了整个文件,得到的是NSArray的NSArray字符串 例如,我得到的是: Loading CSV from: ( ( Last, First, Middle, Nickname, Gender, City, Age, Email ),
Loading CSV from: (
(
Last,
First,
Middle,
Nickname,
Gender,
City,
Age,
Email
),
(
Doe,
John,
Awesome,
"JD",
M,
"San Francisco",
"20",
"john@john.doe"
),
我怎样才能像马特·汤普森那样,将其排序为Person对象并使用NSPredicate进行过滤呢
下面是初始化解析器的方法:
//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];
}];
首先,定义合适的
人员
类别:
@interface Person : NSObject
@property(copy, nonatomic) NSString *firstName;
@property(copy, nonatomic) NSString *lastName;
// ...
@property(nonatomic) int age;
// ...
@end
然后,通过枚举
myFile
array。在块内部,行
是单行的“子数组”:
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];
感谢您的解释和简化过程!