likecatfood
likecatfood

Reputation: 75

Objective c: How to add strings from .txt file to NSArray?

I have weekdays.txt file in my project. There are days of the week with spaces among them in this file. And my code is not working.

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

Where can be the problem? thanks.

Upvotes: 1

Views: 837

Answers (2)

AlexUseche
AlexUseche

Reputation: 150

You could also do the following:

// 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);

And that's it. The NSLog will actually output whatever you had typed inside the file just to prove this works.

Upvotes: 0

jlstrecker
jlstrecker

Reputation: 5033

What format is your file?

The documentation for -initWithContentsOfFile says path should be "The path to a file containing a string representation of an array produced by the writeToFile:atomically: method." That would be a property list.

If your file is not a property list, you could read the file into an NSString (+[NSString stringWithContentsOfFile:encoding:error:]) and then split it into words (-[NSArray componentsSeparatedByString:]).

Upvotes: 4

Related Questions