당신은 문자열의 배열로 파일을 구문 분석 할 및 이 배열의 각 요소에 키를 할당하십시오. 이것은 올바른 방향으로 나아갈 수 있도록 도와줍니다.
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]];
가 단지 배열이 아닌가요? 키순과 동일한 순서로 읽는 경우 해시 테이블을 구현할 필요가 없습니다. – dreamlax