【问题标题】:Cocoa-Touch - Loading a text file into an arrayCocoa-Touch - 将文本文件加载到数组中
【发布时间】:2010-07-21 00:47:30
【问题描述】:

我的代码有什么问题.. 我希望它读取文本文件,例如

项目1

项目2

项目3

项目4

项目5

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

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

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

我将 txt 文件放入我的项目中并复制到目的地。

【问题讨论】:

    标签: objective-c cocoa debugging


    【解决方案1】:

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

    [[NSFileManager defaultManager] isReadableFileAtPath:aPath];
    

    其次,您的文件中有什么。 initWithContentsOfFile 的行为:

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

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

    回应

    您不能使用 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];
    

    【讨论】:

    • 嗯,我遇到了一个错误.. encoding: NSUTF8StringEncoding]]; 它说它在 ] 之前缺少一个 : 你是否缺少参数?
    • @shorty876:不,他开头的 [ 字符太多了。
    • 哦,哇,我试图自己修复它,但我只看右括号......谢谢
    • @Jeremy:哎呀,我本来打算放一个自动释放的,但在我查找 UTF8 常量时忘记了!谢谢。
    • 打印这是....."[", " {", " \"name\": \"Afghanistan\",", " \"dial_code\": \"+93\",", " \"code\": \"AF\"", " },",
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 2012-08-22
    相关资源
    最近更新 更多