Objective c 目标c:如何将.txt文件中的字符串添加到NSArray?
我的项目中有weekdays.txt文件。此文件中有一周中的几天,其中有空格。我的代码不起作用Objective c 目标c:如何将.txt文件中的字符串添加到NSArray?,objective-c,Objective C,我的项目中有weekdays.txt文件。此文件中有一周中的几天,其中有空格。我的代码不起作用 NSString* path = [[NSBundle mainBundle] pathForResource:@"weekdays" ofType:@"txt"]; weekdaysDataSource = [[NSArray alloc] initWithContentsOfFile:path]; 问题出在哪里?谢谢。您的文件是什么格式的 -initWithContentsOfFile的文档中说
NSString* path = [[NSBundle mainBundle] pathForResource:@"weekdays" ofType:@"txt"];
weekdaysDataSource = [[NSArray alloc] initWithContentsOfFile:path];
问题出在哪里?谢谢。您的文件是什么格式的
-initWithContentsOfFile
的文档中说路径
应该是“包含writeToFile:atomicaly:method生成的数组的字符串表示的文件路径”。这将是一个属性列表
如果文件不是属性列表,则可以将文件读入NSString(
+[NSString stringWithContentsOfFile:encoding:error:
),然后将其拆分为单词(-[NSArray Components SeparatedByString:
) 您的文件是什么格式的
-initWithContentsOfFile
的文档中说路径
应该是“包含writeToFile:atomicaly:method生成的数组的字符串表示的文件路径”。这将是一个属性列表
如果文件不是属性列表,则可以将文件读入NSString(
+[NSString stringWithContentsOfFile:encoding:error:
),然后将其拆分为单词(-[NSArray Components SeparatedByString:
) 您还可以执行以下操作:
// 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实际上会输出您在文件中键入的任何内容,以证明其有效性。您还可以执行以下操作:
// 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实际上会输出您在文件中键入的任何内容,以证明这是有效的