Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Read file lines into array

Tags:

arrays

file

ios

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);
}
like image 210
Flatlyn Avatar asked Mar 19 '12 05:03

Flatlyn


2 Answers

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];
like image 165
Ilanchezhian Avatar answered Nov 02 '22 02:11

Ilanchezhian


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

like image 25
Ravi Avatar answered Nov 02 '22 02:11

Ravi