12

I have some sample code from Tuaw which is probably 3 releases old ;) The compiler is issuing a warning that the method is deprecated, but I do not see that mentioned in the SDK docs. If it is deprecated, there must be an alternative approach or replacement method. Does anyone know what the replacement is for this method?

The specific code was:

NSArray *crayons = [[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"crayons" ofType:@"txt"]] componentsSeparatedByString:@"\n"];

The modified code (in discrete idiot steps - and no error handling) is:

NSError *error;
NSString *qs = [[NSBundle mainBundle] pathForResource: @"crayons" ofType: @"txt"];
NSString *ps = [[NSString alloc] stringWithContentsOfFile:qs encoding:NSUTF8StringEncoding error: &error];
NSArray *crayons = [[NSArray alloc] arrayWithContentsOfFile: ps];               
mobibob
  • 8,670
  • 20
  • 82
  • 131

2 Answers2

18

Here's an example, adding to Carl Norum's correct answer.

Note the ampersand & prepended to the passed error variable.

// The source text file is named "Example.txt". Written with UTF-8 encoding.
NSString* path = [[NSBundle mainBundle] pathForResource:@"Example"
                                                 ofType:@"txt"];
NSError* error = nil;
NSString* content = [NSString stringWithContentsOfFile:path
                                              encoding:NSUTF8StringEncoding
                                                 error:&error];
if(error) { // If error object was instantiated, handle it.
    NSLog(@"ERROR while loading from file: %@", error);
    // …
}

Bit of advice… Always make an attempt to know the character encoding of your file. Guessing is risky business.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
18

A more capable method replaced the old one. Use:

+ (id)stringWithContentsOfFile:(NSString *)path
                  usedEncoding:(NSStringEncoding *)enc
                         error:(NSError **)error

Enjoy! Check out the documentation for more information.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • And be sure to handle the error if the BOOL returns NO for success. Lots of sample code does not show that. – uchuugaka Apr 19 '14 at 08:39