0

I am new to this development.

I want to store complete object of a class into my database. Actually I am creating application where user can add multiple views to parent view and want to save it, so that next time when user fetches it, he will get what ever he has saved i.e. views to parent view previously.

Any logic or suggestion on same will really be helpful,

Thanks in advance

P.J
  • 6,547
  • 9
  • 44
  • 74

3 Answers3

3

Any object you want to save will need to conform to the NSCoder protocol. Keep in mind that if you have custom objects within your parent object that they to will need to conform to NSCoder. Add the following methods to your custom class(es).

- (id)initWithCoder:(NSCoder *)coder {
  _inventory = [[coder decodeObjectForKey:@"inventory"] retain];

  return self;
}

- (void)encodeWithCoder:(NSCoder *) encoder{
  [encoder encodeObject:_inventory forKey:@"inventory"];
} 

In the example above I want to encode a player's inventory. If the inventory contains custom objects (as opposed to a bunch of NSStrings for example) they'll also need their own NSCoder methods.

Below I turn it into something you can save out to NSUserDefaults. Adjust appropriately to store in a DB. Keep in mind if you want to send NSData over the wire to store in a DB you'll want to convert it to Base64 and possibly compress it.

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData * encodedObject = [NSKeyedArchiver archivedDataWithRootObject:rootObject];

[defaults setObject:encodedObject forKey:kSaveArchiveKey];
[defaults synchronize];

To go the other way, you'll want to grab your NSData, do whatever magic on it as I described above (base64, compression) and unarchive.

PlayerInventory *inventory = [NSKeyedUnarchiver unarchiveObjectWithData:playerInventoryData]
Sandoze
  • 472
  • 2
  • 9
1

You should choose between NSCoding and Core Data depending on your exact needs. See this post for more info: NSCoding VS Core data

Community
  • 1
  • 1
MrTJ
  • 13,064
  • 4
  • 41
  • 63
  • Thanks for your answer, can you just provide a sample code on how actually I can store them. – P.J Mar 08 '12 at 10:32
  • @Prateek, Apple provides lots and lots of sample code. Go to the developer center and look. – Jim Mar 08 '12 at 16:46
0

You can store state(value of any attributes) of any object in database. You should use NSCoding.Example here

Vignesh
  • 10,205
  • 2
  • 35
  • 73
  • Thanks for your answer, can you just provide a sample code on how actually I can store class object using NSCoding – P.J Mar 08 '12 at 10:31