微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

项目1

项目2

项目3

项目4

项目5

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

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

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

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

解决方法

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

[[NSFileManager defaultManager] isReadableFileAtPath:aPath];

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

The array representation in the file identified by aPath must contain only property list objects (Nsstring,NSData,NSArray,or NSDictionary objects).

您的文件是有效的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];

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐