How do I store a class object to file?

Discussion in 'iOS Programming' started by resting, Sep 9, 2012.

  1. resting macrumors member

    Aug 15, 2011
    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?
  2. ArtOfWarfare macrumors 604


    Nov 26, 2007
    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...
  3. KnightWRX macrumors Pentium


    Jan 28, 2009
    Quebec, Canada
    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).
  4. firewood macrumors 604

    Jul 29, 2003
    Silicon Valley
  5. charlieegan3 macrumors 68020


    Feb 16, 2012
    You want to save the values for all the properties/data items of the class.

Share This Page