Reading a text file in Objective-C

Viro

Registered
I'm trying to figure out how I would read a text file, line by line in Objective-C. I've looked at NSFile, but I think that is for dealing with binary files. There isn't corresponding NSTextFile or something that looks like it deals with text files.

What is the usual way of dealing with text files? Do you just use NSString's methods like initWithContentsOfFile and stringWithContentsOfFile? These methods are only available on 10.4 and later. What options do you have if you aren't using 10.4?
 
I use NSData's dataWithContentsOfFile, and then pass that to NSString's initWithData:encoding. That way will work pre-Tiger. I guess that would be a bit inefficient with large files, since you'd be duplicating the entire contents of the file in memory, but it gets the job done, anyway.
 
Thanks for the info. It doesn't sound too efficient, but I guess that will have to do. I'm just glad my files don't exceed 100 MB in size.
 
Actually IIRC large files are not read into memory. They are mmap-ed and faulted in as need be. That is part of the reason NSData is a class cluster, to support optimizations like that one.
 
What about NSString's initWithContentsOfFile(I think)? I came across this and it couldn't be easier. Does anyone know if this has the same optimizations if the file is large?
 
That method is only available in Tiger and later versions of OS X. I mentioned in the original post and was interested to see if there were other ways that weren't tiger specific.
 
Back
Top