我正在尝试编写一个例程,该例程从制表符分隔的文件中将数百条客户记录导入到 NSArrayController 中。
这是我的初始代码:
NSString *stringFromFile = [NSString stringWithContentsOfFile:[fileURL path]
encoding:NSUTF8StringEncoding error:&error];
NSArray *paragraphsArray = [stringFromFile componentsSeparatedByString:@"\r"];
NSMutableDictionary *destDict = [[NSMutableDictionary alloc] init];
int i;
for (i = 0; i <= [paragraphsArray count]-1; i++) {
NSString *currentParagraph = [paragraphsArray objectAtIndex:i];
if ([currentParagraph length ] > 4) {
NSArray *elementsArray = [currentParagraph componentsSeparatedByString:@"\t"];
if ([elementsArray count] > 0) {
currentSerial++;
[destDict setObject:[NSString stringWithFormat:@"%ld",currentSerial]
forKey:@"idSerial"];
[destDict setObject:[elementsArray objectAtIndex:1]
forKey:@"destRazaoSocial"];
[destDict setObject:[elementsArray objectAtIndex:2]
forKey:@"destLogradouro"];
[destDict setObject:[elementsArray objectAtIndex:3]
forKey:@"destLogradouroNro"];
/// repeat this for every field...
//Add the record:
[destArrayController addObject:destDict];
}
}
}
这段代码导致插入错误的记录,如果我在一个例子中有4条记录,插入的4条记录将与最后一条记录具有相同的内容。
但是,如果我将代码更改为此,分配 destDict 并在每个循环中丢弃它,它就可以工作:
NSString *stringFromFile = [NSString stringWithContentsOfFile:[fileURL path]
encoding:NSUTF8StringEncoding error:&error];
NSArray *paragraphsArray = [stringFromFile componentsSeparatedByString:@"\r"];
int i;
for (i = 0; i <= [paragraphsArray count]-1; i++) {
NSString *currentParagraph = [paragraphsArray objectAtIndex:i];
if ([currentParagraph length ] > 4) {
NSArray *elementsArray = [currentParagraph componentsSeparatedByString:@"\t"];
if ([elementsArray count] > 0) {
NSMutableDictionary *destDict = [[NSMutableDictionary alloc] init];
currentSerial++;
[destDict setObject:[NSString stringWithFormat:@"%ld",currentSerial]
forKey:@"idSerial"];
[destDict setObject:[elementsArray objectAtIndex:1]
forKey:@"destRazaoSocial"];
[destDict setObject:[elementsArray objectAtIndex:2]
forKey:@"destLogradouro"];
[destDict setObject:[elementsArray objectAtIndex:3]
forKey:@"destLogradouroNro"];
/// repeat this for every field...
//Add the record:
[destArrayController addObject:destDict];
[destDict release];
}
}
}
这可行,但对我来说看起来并不优雅。你能告诉我正确的方法吗?