我的txt文件看起来像这样
Blue|Big
Red|medium
Yellow|small
从这个txt文件创建NSDictionary的最佳方法是什么?
我考虑过componentsSeparatedByString:@" |"
输出应该是
@{@"Blue": @"Big", @"Red": @"medium", @"Yellow": @"small"}
编辑:正确格式化文本文件
答案 0 :(得分:1)
这应该做:
NSString* text = [NSString stringWithContentsOfURL:someURL encoding:NSUTF8StringEncoding error:NULL];
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
[text enumerateLinesUsingBlock:^(NSString *line, BOOL *stop){
NSArray* keyAndValue = [line componentsSeparatedByString:@"|"];
NSString* key = keyAndValue.firstObject;
NSString* value = keyAndValue.lastObject;
dict[key] = value;
}];
答案 1 :(得分:0)
试试这样: -
//Extracting File Path
NSString* yourFile = [[NSBundle mainBundle]
pathForResource:filePath ofType:@"txt"];
//Reading File
NSString* fileContents =
[NSString stringWithContentsOfFile:yourFile
encoding:NSUTF8StringEncoding error:nil];
//Splitted using pipeline which will return array
NSArray* allLinedStrings =
[fileContents componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSMutableDictionary *dict=[NSMutableDictionary dictionary];
for (NSString *str in allLinedStrings)
{
NSArray *ar=[str componentsSeparatedByString:@"|"];
[dict setObject:ar[1] forKey:ar[0]];
}
NSLog(@"%@",dict);