IOS reading strings in an array

I have a file containing several thousand words in separate lines. I need to load all these words into separate elements inside the array, so the first word will be Array [0], the second will be Array [1], etc.

I found some sample code elsewhere, but Xcode 4.3 says it uses discounted calls.

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

NSEnumerator *nse = [lines objectEnumerator];

while(tmp = [nse nextObject]) {
    NSLog(@"%@", tmp);
}
+5
source share
2 answers

Yes, + (id)stringWithContentsOfFile:(NSString *)pathout of date.

See Apple documentation for NSString

Use instead + (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error

Use the following:

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];
+18
source

Mark it . You may need to use the updated method.

+1
source

All Articles