iOS将文件行读入数组

6
我有一个包含成千上万个单独行的文件。我需要将所有这些单词加载到数组内的单独元素中,因此第一个单词将是Array [0],第二个将是Array [1]等等。
我在其他地方找到了一些示例代码,但Xcode 4.3表示它正在使用不推荐使用的调用。
NSString *tmp;
NSArray *lines;
lines = [[NSString stringWithContentsOfFile:@"testFileReadLines.txt"] 
                   componentsSeparatedByString:@"\n"];

NSEnumerator *nse = [lines objectEnumerator];

while(tmp = [nse nextObject]) {
    NSLog(@"%@", tmp);
}
2个回答

19

是的,+ (id)stringWithContentsOfFile:(NSString *)path已经被弃用。

请参考苹果文档中的NSString

改为使用 + (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error

用法如下:

lines = [[NSString stringWithContentsOfFile:@"testFileReadLines.txt"
                                   encoding:NSUTF8StringEncoding 
                                      error:nil] 
            componentsSeparatedByString:@"\n"];

更新: - 感谢JohnK

NSCharacterSet *newlineCharSet = [NSCharacterSet newlineCharacterSet];
NSString* fileContents = [NSString stringWithContentsOfFile:@"testFileReadLines.txt"
                                                   encoding:NSUTF8StringEncoding
                                                      error:nil];
NSArray *lines = [fileContents componentsSeparatedByCharactersInSet:newlineCharSet];

1
为了通用性,您应该使用componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet],即:NSString * contents = [NSString stringWithContentsOfFile:@“testFileReadLines.txt”encoding:NSUTF8StringEncoding error:nil]; NSArray * lines = [contents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]; - JohnK

1

请检查this。您可能需要使用更新的方法。


3
谢谢您的帮助。我向Aadhira提供了正确答案,因为它略微更加完整。 - Flatlyn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接