How do I store a class object to file?

Discussion in 'iPhone/iPad Programming' started by resting, Sep 9, 2012.

  1. macrumors member

    Joined:
    Aug 15, 2011
    #1
    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. macrumors 603

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #2
    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. macrumors Pentium

    KnightWRX

    Joined:
    Jan 28, 2009
    Location:
    Quebec, Canada
    #3
    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) :

    http://www.raywenderlich.com/1914/how-to-save-your-app-data-with-nscoding-and-nsfilemanager

    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. macrumors 603

    Joined:
    Jul 29, 2003
    Location:
    Silicon Valley
    #4
  5. macrumors 68020

    charlieegan3

    Joined:
    Feb 16, 2012
    Location:
    U.K
    #5
    You want to save the values for all the properties/data items of the class.
     

Share This Page