6

I have a file containing a couple thousands words on individual lines. I need to load all of these words into separate elements inside an array so first word will be Array[0], second will be Array[1] etc.

I found some sample code elsewhere but Xcode 4.3 says it's using depreciated calls.

NSString *tmp;
NSArray *lines;
lines = [[NSString stringWithContentsOfFile:@"testFileReadLines.txt"] 
                   componentsSeparatedByString:@"\n"];

NSEnumerator *nse = [lines objectEnumerator];

while(tmp = [nse nextObject]) {
    NSLog(@"%@", tmp);
}

2 Answers 2

19

Yes, + (id)stringWithContentsOfFile:(NSString *)path has been deprecated.

See Apple's documentation for NSString

Instead use + (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error

Use as follows:

lines = [[NSString stringWithContentsOfFile:@"testFileReadLines.txt"
                                   encoding:NSUTF8StringEncoding 
                                      error:nil] 
            componentsSeparatedByString:@"\n"];

Update: - Thanks to JohnK

NSCharacterSet *newlineCharSet = [NSCharacterSet newlineCharacterSet];
NSString* fileContents = [NSString stringWithContentsOfFile:@"testFileReadLines.txt"
                                                   encoding:NSUTF8StringEncoding
                                                      error:nil];
NSArray *lines = [fileContents componentsSeparatedByCharactersInSet:newlineCharSet];
Sign up to request clarification or add additional context in comments.

1 Comment

For generality you should use componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet], viz.: NSString* contents = [NSString stringWithContentsOfFile:@"testFileReadLines.txt" encoding:NSUTF8StringEncoding error:nil]; NSArray *lines = [contents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];.
1

Check this. You might have to use an updated method.

1 Comment

Thanks for the help. Gave Aadhira the correct answer for was slightly more complete.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.