简体   繁体   English

从txt文件中读取字符串到iOS中的NSArrays

[英]Reading strings from txt files into NSArrays in iOS

After much reading it seems that, really, the only way to read a number of lines from a text file into an NSArray is with this: 经过多次阅读后,似乎真的,从文本文件中读取多行代码到NSArray的唯一方法是:

NSString *myfilePath = [[NSBundle mainBundle] pathForResource:@"poem" ofType:@"txt"];

NSString *linesFromFile = [[NSString alloc] initWithContentsOfFile:myfilePath encoding:NSUTF8StringEncoding error:nil];

myArrayOfLines = [NSArray alloc];
myArrayOfLines = [linesFromFile componentsSeparatedByString:@"\n"];

NSArrays have a method for initWithContentsOfFile but I have not seen any examples of how to use this. NSArrays有一个initWithContentsOfFile的方法,但我还没有看到任何如何使用它的例子。 I have read some posts that state that the file must be a plist and not a generic txt file. 我已经阅读了一些帖子,说明该文件必须是plist而不是通用的txt文件。

Is this really the case? 这是真的吗? Is there a way to read lines (terminated with \\n ) directly into an NSArray ? 有没有办法直接读取行(以\\n结尾)到NSArray

You have it right, except the line myArrayOfLines = [NSArray alloc]; 你没错,除了线myArrayOfLines = [NSArray alloc]; which is useless. 这没用。 Don't bother with plist if you already have a good txt file. 如果你已经有一个好的txt文件,请不要打扰plist。 But for curiosity, here is a link which explains how it works with plist files : link 但是为了好奇,这里有一个链接,解释了它如何与plist文件一起工作: 链接

Also, if you don't use ARC, you'll have some leaks, but that's another question, and we don't have the whole code, so I might be wrong. 此外,如果你不使用ARC,你会有一些泄漏,但这是另一个问题,我们没有完整的代码,所以我可能错了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM