StackCoder
StackCoder

Reputation: 81

Serialization and Deserialization of NSMutableArray for objects of custom classes

Platform: XCode5 Language: Objective C Project: An iOS App

I am basically from Java and C# background and this being my first iOS App, I am feeling severely limited.

I am working on an application where I need to store user data. There are about 10 data model classes, with some classes having properties of custom types. Total number of records across all models will be less than 1000 during app usage lifetime. Basically, on any single date, only 1 object of each date model can be generated. There will not be much querying to saved data, apart from basic query like "show one record of Data Model type X for Date d".

I am thinking of using a simple approach where I serialize the records of each Data Model in a simple text file or something using serialization. So whenever a new record is created, it is serialized and written to a file containing previous such records.

I understand that I'll have to deserialize all existing records from the file into an NSMutableArray, add new record, and then serialize the new NSMutableArray back. I would prefer to create a class with static functions to do so, using either Generics or NSMutableObject.

Now, the questions are: 1. What is the best way to serialize/deserialize here considering my scenario explained above. I have read about Property Lists and NScoding protocol. I am inclined towards using NSCoding protocol. Will it be the right approach?

  1. I read that I'll need to implement initWithCoder function where all properties that need to be serialized will be mentioned as key/value pairs. What will I do here in case where some properties are of custom type? Example, property named length of type "distance" for a class named "room", where "distance" is a class with 2 properties of type integer - feet and inches. And yes, this distance-room thing is just an example to understand the solution to my problem.

  2. Any more details on serialization/deserialization objects of custom types with some properties of custom types again, will be appreciated.

Upvotes: 2

Views: 507

Answers (1)

Eugene Dudnyk
Eugene Dudnyk

Reputation: 6030

The simpliest way to serialize something to NSData in iOS is to use NSKeyedArchiver/NSKeyedUnarchiver. For custom objects you will need to implement NSCoding protocol.

Note that objects you store in the array must also support NSCoding.

But, when deserializing, in place of NSMutableArray objects you will receive immutable NSArray objects. To obtain mutable instance you will have to make

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        myMutableArray = [NSMutableArray arrayWithArray:[aDecoder decodeObjectForKey:@"myMutableArray"]];
    }
    return self;
}

Upvotes: 2

Related Questions