0
votes

I am looking to save an elaborate multi-leveled custom object into NSUserDefaults. My setup of custom classes is as follow's:

  • Instructor
    • @property (strong, nonatomic) NSString *instructorName;
    • @property (strong, nonatomic) NSMutableArray *classes; // Array of class object's
  • Class
    • @property (strong, nonatomic) NSString *className;
    • @property (strong, nonatomic) NSMutableArray *students; // Array of student object's
  • Student
    • @property (strong, nonatomic) NSString *studentName;
    • @property (nonatomic) NSUInteger studentNumber;
    • @property (nonatomic) NSInteger studentMoney;

I am needing to save the top level "Instructor" object into NSUserDefault's so that I can access the entire tier of data below it. I have referenced this post, but I am needing a little bit more help on getting it solved. In that example he show's two different classes' and some method's to go along with it. Are those method's written into the different custom classes themselves? How would I go about practically using that for my application?

I am needing to save a single "Instructor" object, which has an array of classes, which are filled with an array of students. How can I save that one instructor object to NSUserDefault's so I can retrieve it and reload it for use?

1
You might reconsider whether this belongs in NSUserDefaults. Is this truly an app preference setting? Or user data.uchuugaka
You need to write encoder and decoder the Objects you want to Save in user defaults. SO that while saving the data will be encoded for saving and it will be decoded for refetching the data.Pavan

1 Answers

2
votes

All the objects (Instructor, Class, and Student) need to adopt and implement the NSCoding protocol. See this post for an implentation. As @uchuugaka said though, it sounds like NSUserDefaults isn't the place to store this data.

You could still serialize the data to disk, but just write it to a separate file. Apple's Archives and Serializations Programming Guide is good reading to learn the basics of this method.

If the object graph you want to save is going to be more complex and you require searching and querying the object graph, e.g. finding the number of students with studentMoney >= 50 with lastName beginning with 'A', then you may want to look into Core Data. However, be aware that Core Data is an advanced framework so it does have a sizable learning curve.