Cocoa-Touch - 将文本文件加载到数组中 [英] Cocoa-Touch - Loading a text file into an array

查看:123
本文介绍了Cocoa-Touch - 将文本文件加载到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码有什么问题..我想要阅读一个文本文件,如

Whats wrong with my code.. I want it to read a text file like

Item1

Item2

Item3

Item4

Item5

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

and parse it into an array so each line is a separate object in thus array.

当您检查控制台时,将打印(null)

When you check the console it prints (null)

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

我将txt文件放在我的项目中,并将其复制到目的地。 p>

I put the txt file in my project and copied it to destination.

推荐答案

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

Firstly, can you verify that the file exists where you are looking and is readable? Use

[[NSFileManager defaultManager] isReadableFileAtPath:aPath];

其次,你的文件是什么。 initWithContentsOfFile

Secondly, what is in your file. The behaviour of initWithContentsOfFile:


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

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

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

Is your file a valid plist xml file?

InResponse

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

You cannot use the NSArray constructor initWithContentsOfFile: to parse a regular text file.

相反,您可以将文件内容读入内存并将其自己解析为数组。例如,您可以使用

Instead you can read the file content into memory and parse it yourself into an array. For your example you could use

//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];

这篇关于Cocoa-Touch - 将文本文件加载到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆