Green Cloak Guy
Green Cloak Guy

Reputation: 24691

Objective-C: Reading from a .rtf file into an array

I've looked around a bit and tried a few things, but none have really worked. What I'm trying to do is create a NSArray of NSStrings, with each array value corresponding to one line from the Rich Text File I'm referencing. At first I tried this:

NSArray* data = [[NSString stringWithContentsOfFile:@"relevantFile.rtf" encoding:4 error:nil] componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];

I've also tried this, because I found it in the iOS developer library:

NSArray* data = [[NSArray alloc] initWithContentsOfFile:@"relevantFile.rtf"];

However, neither of these has worked for me. A few lines later in the code, in order to diagnose errors, I have the following code:

for(int i = 0; i < [data count]; i++)
{
NSLog(@"%@", [data objectAtIndex: i]);
}

...for which NSLog is printing "(null)". I'm not entirely sure what I'm doing wrong here -- should I be using mutable strings or arrays, or is there some better way to go about this that I don't know about?

Upvotes: 1

Views: 1761

Answers (1)

ipmcc
ipmcc

Reputation: 29886

That first line you posted should do it. My guess would be that it's not finding the file. Not specifying an absolute path, the app will look in the current directory which is probably NOT where the file is.

If the file is a resource that is compiled into your app bundle, you can use the following code to obtain the path to it:

NSString* path = [[NSBundle mainBundle] pathForResource: @"relevantFile" ofType: @"rtf"]
NSArray* data = [[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil] componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];

Upvotes: 2

Related Questions