我想要实现的是将 csv 文件转换为自定义对象数组,但是,我对此的尝试似乎导致数组中的所有对象都作为同一个对象返回(数组中的最后一个对象)。
在我进一步解释之前,这里是代码:
- (NSArray *)arrayFromCSVFileName:(NSString *)csvFileName fileType:(NSString *)fileType {
// Convert the file into an NSData object
NSString *studentFilePath = [[NSBundle mainBundle] pathForResource:csvFileName ofType:fileType];
NSData *studentData = [NSData dataWithContentsOfFile:studentFilePath];
// Convert the NSData into an NSString
NSString *csvString = [[NSString alloc] initWithData:studentData encoding:NSUTF8StringEncoding];
// Split each record (line) in the csvDataString into an individual array element (split on the newline character \n)
NSArray *csvArray = [csvString componentsSeparatedByString:@"\n"];
// Create an array to hold the parsed CSV data
NSMutableArray *parsedCSVArray = [[NSMutableArray alloc] init];
NSMutableArray *elementArray = [[NSMutableArray alloc] init];
CGSElement *elementToAdd = [[CGSElement alloc] init];
// Loop through each line of the file
for (int i = 0; i < [csvArray count]; i++) {
// Get a reference to this record (line) as a string, and remove any extranous new lines or alike
NSString *csvRecordString = [[csvArray objectAtIndex:i] stringByReplacingOccurrencesOfString:@"\r" withString:@""];
// Split the line by the comma delimeter
NSArray *csvRecordArray = [csvRecordString componentsSeparatedByString:@","];
// Check that there are actually fields (i.e. this is not a blank line)
if ( ([csvRecordArray count] > 0) && ([[csvRecordArray objectAtIndex:0] length] > 0) ) {
elementToAdd.mass = [[csvRecordArray objectAtIndex:1] floatValue];
elementToAdd.atomicNumber = [[csvRecordArray objectAtIndex:0] intValue];
elementToAdd.name = [csvRecordArray objectAtIndex:2];
elementToAdd.symbol = [csvRecordArray objectAtIndex:3];
elementToAdd.period = [[csvRecordArray objectAtIndex:4] intValue];
[elementArray addObject:elementToAdd];
}
}
for (int i = 0; i < [elementArray count]; i++) {
NSLog(@"%i", i);
CGSElement *current = [elementArray objectAtIndex:i];
NSLog(@"Name = %@", current.name);
}
// Return the parsed array
return elementArray;
}
有问题的自定义对象是 CGSElement 对象,我试图用它来填充elementArray
。但是,我的调试代码(以下代码部分):
for (int i = 0; i < [elementArray count]; i++) {
NSLog(@"%i", i);
CGSElement *current = [elementArray objectAtIndex:i];
NSLog(@"Name = %@", current.name);
}
结果,不是返回所有正确的元素名称,而是返回最后一个元素(将其放在上下文中,ununoctium)118 次。
经过一些测试,我可以放心地说,直到这一点之后:
elementToAdd.mass = [[csvRecordArray objectAtIndex:1] floatValue];
elementToAdd.atomicNumber = [[csvRecordArray objectAtIndex:0] intValue];
elementToAdd.name = [csvRecordArray objectAtIndex:2];
elementToAdd.symbol = [csvRecordArray objectAtIndex:3];
elementToAdd.period = [[csvRecordArray objectAtIndex:4] intValue];
所有元素都被正确定义,而不是一遍又一遍地定义相同的元素。
不用说,我很困惑为什么它会一遍又一遍地返回同一个对象。任何帮助,将不胜感激。