我正在嘗試編寫一個從製表符分隔的文件導入數百個客戶記錄到NSArrayController的例程。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個記錄的例子中,四個記錄插入將具有相同內容的最後一個記錄。
但是,如果我的代碼改變這一點,allocing 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];
}
}
}
這工作,但它看起來並不優雅給我。 您是否真的好好告訴我這樣做的正確方法?