从文本文件中读取 - 目标C. [英] Reading from text file - Objective C

查看:119
本文介绍了从文本文件中读取 - 目标C.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试熟悉目标C,我目前的目标是读取文本文件中的项目列表并将它们存储在NSString数组中。

I am trying to familiarize myself with objective C, and my current goal is to read a list of items in a text file and store them in a NSString array.

目前这就是我所拥有的:

Currently this is what I have:

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"myList" ofType:@"txt"];
NSData* data = [NSData dataWithContentsOfFile:filepath];
NSString* string = [[NSString alloc] initWithBytes:[data bytes]
                                             length:[data length]
                                           encoding:NSUTF8StringEncoding];

NSString* delimiter = @"\n";
listArray = [string componentsSeparatedByString:delimiter];

我不确定这是否重要,但 myList.txt 在我的支持文件中。

I am not sure if this matters, but myList.txt is in my Supporting Files.

目前,我的列表中只有一个项目。但是我甚至无法将这1项存入我的 listArray

At the moment, I only have one item in my list. However I am unable to store even that 1 item into my listArray.

我确信这是愚蠢的事情我很想念,我只是对Objective C的新手。

I am sure it is something silly that I am missing, I am just new to Objective C.

编辑:
我为之前没有提及此道歉。我没有收到任何错误。我的数组只是null。

I apologize for not mentioning this earlier. I AM NOT receiving any sort of error. My array is just null.

推荐答案

我建议稍微简化,这可能会解决你的问题,因为我不能说出你的问题是什么。从信息中我不确定你是否在阅读时获得了正确的文件内容。

I'm going to suggest a little simplification which might solve your problem since I can't say what your problem is. From the information I'm not sure if you are getting the proper file contents when reading it in or not.

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"myList" ofType:@"txt"];
NSError *error;
NSString *fileContents = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:&error];

if (error)
    NSLog(@"Error reading file: %@", error.localizedDescription);

// maybe for debugging...
NSLog(@"contents: %@", fileContents);

NSArray *listArray = [fileContents componentsSeparatedByString:@"\n"];
NSLog(@"items = %d", [listArray count]);  

这篇关于从文本文件中读取 - 目标C.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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