Cocoa-Touch - 将文本文件加载到数组中

use*_*419 6 debugging cocoa objective-c

我的代码有什么问题..我希望它能读取像这样的文本文件

项目1

项目2

项目3

项目4

项目5

并将其解析为一个数组,因此每一行都是这样的数组中的一个单独的对象.

检查控制台时,它会打印出来 (null)

-(void)parseIntoArray{ //parse the files into seprate arrays.
    allPools = [[NSMutableArray alloc] initWithContentsOfFile:@"ALL_POOLS_NAMES"];
    NSLog(@"%@",allPools);
}
Run Code Online (Sandbox Code Playgroud)

我将txt文件放在我的项目中并将其复制到目标.

Aku*_*ete 13

首先,您是否可以验证文件是否存在于您所查找的位置且可读?使用

[[NSFileManager defaultManager] isReadableFileAtPath:aPath];
Run Code Online (Sandbox Code Playgroud)

其次,你的文件中有什么.initWithContentsOfFile的行为:

由aPath标识的文件中的数组表示必须仅包含属性列表对象(NSString,NSData,NSArray或NSDictionary对象).

您的文件是有效的plist xml文件吗?

InResponse

您不能使用NSArray构造函数initWithContentsOfFile:来解析常规文本文件.

相反,您可以将文件内容读入内存并自行解析为数组.对于您可以使用的示例

//pull the content from the file into memory
NSData* data = [NSData dataWithContentsOfFile:aPath];
//convert the bytes from the file into a string
NSString* string = [[[NSString alloc] initWithBytes:[data bytes]
                                            length:[data length] 
                                          encoding:NSUTF8StringEncoding] autorelease];

//split the string around newline characters to create an array
NSString* delimiter = @"\n";
NSArray* items = [string componentsSeparatedByString:delimiter];
Run Code Online (Sandbox Code Playgroud)