您需要将文件解析为一个字符串数组,并用一个键分配该数组中的每个元素。这也许能帮你找到正确的方向。
NSString *wholeFile = [NSString stringWithContentsOfFile:@"filename.txt"];
NSArray *lines = [wholeFile componentsSeparatedByString:@"\n"];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:[lines count]];
int counter = 1;
for (NSString *line in lines)
{
if ([line length])
{
[dict setObject:line forKey:[NSString stringWithFormat:"%d", counter]];
// If you want `NSNumber` as keys, use this line instead:
// [dict setObject:line forKey:[NSNumber numberWithInt:counter]];
counter++;
}
}
请记住,这不是解析文件的最有效方法。它还使用不推荐的方法
stringWithContentsOfFile:
.
要恢复线路,请使用:
NSString *myLine = [dict objectForKey:@"1"];
// If you used `NSNumber` class for keys, use:
// NSString *myLine = [dict objectForKey:[NSNumber numberWithInt:1]];