将文件读入数组

Wal*_*ker 6 arrays cocoa file objective-c

我有一个由换行符分隔的单词/短语文件.我需要获取文件并将每个单词/短语读入数组.到目前为止我有这个:

    NSFileHandle *wordsFile = [NSFileHandle fileHandleForReadingAtPath:[[NSBundle     mainBundle] pathForResource:@"WordList"
                                                                                                           ofType:nil]];
    NSData *words = [wordsFile readDataToEndOfFile];
    [wordsFile closeFile];
    [wordsFile release];
Run Code Online (Sandbox Code Playgroud)

但是我不确定这是否正确,如果是的话,从哪里开始.

此外,茶馆的答案

NSString componentsSeparatedByCharactersInSet:NSCharacterSet newlineCharacterSet

效果很好,但只有10.5. 如何为10.4复制此行为?

tea*_*bot 11

这是一个应该工作的方法 - 我将省略一个实际的代码示例,因为实现应该相当简单,具体如下:

从您的文件构造NSString:

NSString stringWithContentsOfFile:encoding:error
Run Code Online (Sandbox Code Playgroud)

使用以下内容将字符串拆分为NSStrings数组:

NSString componentsSeparatedByCharactersInSet:
NSCharacterSet newlineCharacterSet
Run Code Online (Sandbox Code Playgroud)

您最终应该使用NSAtrray NSStrings,每个字符串包含文件中的一行.


mic*_*moo 11

只是为了完整(因为我很无聊)这里有一个完整的例子,基于teabot的帖子:

    NSString *string = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
                                                            pathForResource:@"file" ofType:@"txt"]];

    NSArray *array = [string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    NSLog(@"%@",array);
Run Code Online (Sandbox Code Playgroud)