2012-07-03 3 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: method». Это будет список свойств.

Если ваш файл не является списком свойств, вы можете прочитать файл в 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 фактически выводит все, что вы набрали внутри файла, чтобы доказать это.

Смежные вопросы