0

I have an object "School" with a mutable array property "favoritesArray" and an NSString property "name".

I have 2 view controllers "HomeViewController" and "FavoritesTableViewController".

In my HomeViewController when a button is tapped this method is called:

self.school=[[School alloc]init]; 
[self.school.favoritesArray addObject:self.school.name];
 NSData *schoolData=[NSKeyedArchiver archivedDataWithRootObject:self.school];
[[NSUserDefaults standardUserDefaults] setObject:schoolData forKey:@"schoolData"];

Then in my "FavoritesTableViewController" I attempt to unarchive the previously archived "school" object so I can access the "favoritesArray".

when a button is tapped in my "FavoritesTableViewController" this method is called:

NSData *dataRetrieved=[[NSUserDefaults standardUserDefaults] objectForKey:@"schoolData"];
School *schoolTwo=[NSKeyedUnarchiver unarchiveObjectWithData:dataRetrieved];
NSLog(@"%lu", (unsigned long)schoolTwo.favoritesArray.count);

However it logs 0 meaning it didn't unarchive the object that was archived in the "HomeViewController".

How do I unarchive the object that was archived in a separate view controller?

rivtracks
  • 43
  • 7

3 Answers3

0

Schoolmust implement NSCoding for NSKeyedArchiver to be able to serialize it.

See http://nshipster.com/nscoding/ for a good introduction to NSCoding and NSKeyedArchiver.

Xavier Rubio Jansana
  • 6,388
  • 1
  • 27
  • 50
  • 1
    If it was not implementing NSCoding it would throw an exception, instead of loggin a zero count! – Merlevede Mar 22 '14 at 18:39
  • I did implement NSCoding. It works perfectly when I unarchive it on the same view controller. – rivtracks Mar 22 '14 at 18:40
  • To me, it should work. Maybe you're seeing the same object when you unserialize in the same view controller? Could you show us the init, initWithCoder and encodeWithCoder methods for School? – Xavier Rubio Jansana Mar 22 '14 at 18:50
0

Whatever you did was right, I think you forgot to initialise the mutable Array.

self.school=[[School alloc]init];
self.school.favoritesArray = [NSMutableArray array];
[self.school.favoritesArray addObject:self.school.name];
santhu
  • 4,796
  • 1
  • 21
  • 29
0

In your School NSObject where you have implemented the NSCoding protocol, have you encoded every objects you have in it? Its necesary to do that, because you are trying to archive the School object

santibernaldo
  • 825
  • 1
  • 11
  • 26