gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:40:57 24 4
gpt4 key购买 nike

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

项目 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 文件吗?

响应

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

关于objective-c - Cocoa-Touch - 将文本文件加载到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3295527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com