View Full Version : How do I store a class object to file?

Sep 9, 2012, 04:27 PM
Before that, I'm not sure if this is the right place to ask newbie question.
If there's a place you know that's great for newbies, please let me know. I need it badly.

Stackoverflow is getting too obsessed with quality questions and reputation points that they tolerate newbie questions no more :(. Hence I'm turning to forums.

Ok, back to question. Say I created a standard NSObject class. Store some user scores in an array to this class.

How can I write this data to a file, so that the app can later retrieve this information even after the app quits?

Sep 9, 2012, 04:58 PM
If you're talking about preserving a few variables within your app, I suggest using NSUserDefaults as they're a pretty simple way of storing / retrieving variables.

If you're talking about having large amounts of data which should be shared outside of your app... I don't think I've ever had to do that... do NSDocuments exist on iOS? They might do that kind of thing...

Sep 9, 2012, 05:03 PM
I recently ran into this specific situation with my own project. It's quite simple really, using NSKeyedArchiver and the NSCoding protocol. I adapted this tutorial to my project and frankly, it was done and debugged in barely half a day (my project is quite large too, this method is very adaptable and flexible) :


You're basically going to need to implement 2 extra methods in your class, -(id) initWithCoder: (NSCoder *)aDecoder and -(void) encodeWithCoder: (NSCoder *)aCoder

Saving and loading is basically creating a NSMutableData set from your object and using that class' - (BOOL)writeToFile: (NSString *)path atomically: (BOOL)useAuxiliaryFile; once your object is stored in an instance using NSKeyedArchiver (which will call your implementation of encoderWithCoder).

Sep 10, 2012, 01:29 PM
Here's an article on archiving eligible objects into a storable data type (NSData) using NSCoding: http://samsoff.es/posts/archiving-objective-c-objects-with-nscoding

Sep 10, 2012, 01:32 PM
You want to save the values for all the properties/data items of the class.