2012-07-03 52 views
1

我在我的项目中有weekdays.txt文件。在这个文件中,它们之间有一天中有空格。而我的代码不起作用。目标c:如何从.txt文件添加字符串到NSArray?

NSString* path = [[NSBundle mainBundle] pathForResource:@"weekdays" ofType:@"txt"]; 
weekdaysDataSource = [[NSArray alloc] initWithContentsOfFile:path]; 

哪里可以解决问题?谢谢。

回答

4

你的文件格式是什么?

-initWithContentsOfFile的文档说path应该是“包含由writeToFile:atomically:方法生成的数组的字符串表示形式的文件的路径。”这将是一个财产清单。

如果您的文件不是属性列表,您可以将该文件读入NSString(+[NSString stringWithContentsOfFile:encoding:error:]),然后将其拆分为单词(-[NSArray componentsSeparatedByString:])。

+0

是的,它的工作。谢谢你的帮助。 – likecatfood

0

你也可以做到以下几点:

// create an NSURL object that holds the path of the file you want to read 

NSURL *fileURL = [NSURL fileURLWithPath:@"/Users/yourname/weekdays.txt"]; 

//Create an NSMutaable string object and use the stringWithContentsOfURL: encoding: error: method to hold whatever might be you have in the text file. 
//Just pass the NSURL object you created in the previous step to as an argument like so 

NSMutableString *text = [NSMutableString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:nil]; 

NSLog(@"The content of the file is: %@", text); 

就是这样。 NSLog实际上会输出你在文件中输入的内容,只是为了证明这一点。

相关问题