Search code examples
objective-ciosnsdatanscodingnsscanner

iOS custom file format loading with NSData & NSCoding


I'm looking for some guidance from some iOS Cocoa programmers as to how one might implement a mechanism to load and parse a custom file format into the model objects that I'll be using in memory. I know there must be many ways to crack this nut, but let me share the basic idea of the current path I've explored, and where I became stuck.

But first, here is the context: say I have an existing file format that I cannot change. It's basically an exotic pipe-delimited format that is broken into various sections, each of which starts something like this:

%n|sectionName

...and the n lines that follow are all pipe-delimited in a way that is unique to that section. Some sections have a pipe-delimited header line, followed by n lines of data (also pipe-delimited), and other sections might just have n pipe-delimited lines. There are several short sections towards the beginning of the file, and then finally there will be one huge section that describes the nodes of a k-ary tree: their parent-child relationships and any data associated with each node. All told the size of these files is in the tens of megabytes, perhaps larger in the future.

Finally, the last bit of context is that I'm fairly new to iOS programming.

I started by using NSFileHandle to obtain a representation of the file as an instance of NSData. This was pretty easy, and upon exploring the NSData interface and trying how to proceed from there, I notice the NSCoding protocol, which purports to be a facility for archiving and serialization of objects into (and from) representations.

I thought this sounded like something I might need, since I tend to think of file formats as being just representations that my model objects can be marshaled into. After digging into the "Archives and Serializations Programming Guide", however, I began to second-guess myself. The API didn't seem to lend itself to what I'm trying to accomplish.

Am I going down a blind alley here? Should I be seeking to subclass NSInputStream instead, or should I take some other approach that I'm missing?


Solution

  • NSCoding is probably the wrong approach. It's designed for serializing and unserializing Objective-C types, not parsing a custom file format.

    There's probably no need to subclass NSInputStream either. Your best bet here is probably to use C's stdio library, in particular fgets to read the lines. If you really want to use NSInputStream or NSFileHandle you certainly can, you'll just have to parse out each line from the string yourself (which is really not that hard).