【发布时间】:2014-03-19 02:28:49
【问题描述】:
我正在尝试使用 NSData 从文本文件中提取信息,然后将其加载到字典中。
首先我创建一个文本文件的字符串,并将每条记录加载到一个数组中。
然后我将每条记录分解为单独的数据元素。
我遇到的问题是,当字典完全填充后,我使用 addObject 将其加载到数组中,它确实成功了。问题是,当下一个循环创建一个新字典时,同一个字典被加载到数组中,我最终得到一个包含所有相同字典的数组,而不是多个不同的字典对象。
我猜我犯了一些简单的错误导致了这个错误。任何帮助将不胜感激。
NSString *clientListFile = [NSURL URLWithString:@"/textfile"];
NSData *clientListDataFile = [NSData dataWithContentsOfFile:clientListFile];
NSString *clientListString = [[NSString alloc]initWithBytes:[clientListDataFile bytes] length:[clientListDataFile length] encoding:NSUTF8StringEncoding];
NSString *returnDelimiter = @"\n";
NSString *commaDelimiter = @",";
NSString *exclamationDelimiter = @"!";
NSArray *keysAndObjects = [[NSArray alloc]init];
NSMutableDictionary *clientList = [[NSMutableDictionary alloc]init];
NSMutableArray *clientListOfDictionaries = [[NSMutableArray alloc]init];
NSArray *sentenceArray = [clientListString componentsSeparatedByString:returnDelimiter];
for (int i = 0; i < [sentenceArray count]; i=i+1) {
[clientList removeAllObjects]; //to start with a fresh dictionary for the next iteration
NSString *recordSentence = [sentenceArray objectAtIndex:i];
NSArray *attributes = [recordSentence componentsSeparatedByString:commaDelimiter];
for (int j = 0; j < [attributes count]; j = j+1) {
NSString *pairsOfItems = [attributes objectAtIndex:j];
//a small arry, of only two objects, the first is the key, the second is the object
keysAndObjects = [pairsOfItems componentsSeparatedByString:exclamationDelimiter];
[clientList setObject:[keysAndObjects lastObject] forKey:[keysAndObjects firstObject]];
}
[clientListOfDictionaries addObject:clientList];
}
当我使用 NSLog 查看字典中的内容时,我重复了同一个字典的多个对象,即使在迭代的早期,我也可以看到代码正在创建单独且唯一的字典。
【问题讨论】:
标签: ios objective-c arrays dictionary