Sunday, June 3, 2007

Reading in individual lines from a file in Objective-C

Okay, I had someone comment on the blog saying that they can get in the string information, they just need to filter out each line. This can be done easily. I also have an application up on the demo server so you can download the source.

It took me a little bit to figure out what the key was to symbolize a new line but it turns out to be a simple \n. So, this is what you have to do:

Read in your text to an NSString object, like so:
  • NSString *info = [NSString stringWithContentsOfFile:@"FilePath.txt"];
Or like this:
  • NSString *info = [[NSString alloc] initWithContentsOfFile:@"FilePath.txt"];
Then you split the string into an array list by doing the following.
  • NSArray *arrayOfLines = [info componentsSeparatedByString:@"\n"];
Now, you will have an array of all the lines in the file. This might actually be one of the slowest means of doing things, since the file has to be read into memory, but it works. And if you have some settings that need to be loaded in through a file, this might just be your thing.

The only bug I had with this was reading in a rich text file. A standard text file works fine doing this method. I hope this helps out. :-)

3 comments:

Anonymous said...

That's because an RTF is not a plain text file: it's a binary file. You are only able to read in text files with this. That includes .cgi, .c, .m, .h, .java, .html, or any other plain-text file like that.

Ryan said...

I learned something new today. I thought that an rtf was a basic text file with special markings, like HTML. :-) But then again, that would be re-inventing the wheel, since that would be exactly like HTML...

Kirubakaran A said...

Awesome. Thanks a lot! This saved lots of time for me.