Objective-C: Reading a file line by line -
What is the proper way to deal with large text files in Objective-C? Suppose I have to read each row separately and treat each line as an NSString. What is the most effective way to do this?
A solution is using the NSString method:
+ (id) stringWithContentsOfFile: (NSString *) path encoding: (NSStringEncoding) Anch Error: (NSError ** ) Error
and then split the line with a new line separator, and then repeat the elements again in the array. However, it is quite inefficient. There is no easy way to treat the file as a stream, instead of just reading it at all, instead of being told in each line? Just like Java's Java.O.Buffard Reader.
This is a great question I think is a good example of @didric The answer is, though it is unfortunate that there is no mechanism for what you really want to do in Cocoa.
You have the amount of n bytes (very similar to java.io.bufferedReader
), but you can convert it to a NSString
by yourself , Then Scan for Newline (or whatever other delimiter), and save any next character, or more characters to read next, if no new line has yet been read. (You can read a NSData , which you can convert to a
NSString
, but this is essentially the same process.)
Apple is the one who can help fill out the details, and if you are going to deal with the uint8_t *
buffers, can also help.
If you want to read the wire in this way (especially in different parts of your program) it would be a good idea to explain this behavior in a class that details for you, or NSInputStream
(this can sub-clinging) and by adding methods that allow you actually read what you want.
For the record, I think it will be a good feature to add, and I will file an increment request for something like that which makes it possible. : -)
Edit: This request expires already exists for a radar 2006 (for ADR-internal people (rdar: // 4742914).
Comments
Post a Comment