NSMutableArray to NSData and NSData to NSMutableArray

Follow these steps :)

Your objects should adopt NSCoding

First thing is elements of your array should adopt the NSCoding protocol. Some classes such as NSString and NSDate already adopt this protocol. So you will be fine if your array is full of objects that already adopt NSCoding. However, you must do a tiny bit of work if you have a custom class of your own or some other class that is not NSCoding friendly. There is a nice tutorial about this. The gist of it is if the elements of your array are objects of type MyClass then adopt NSCoding in the header file,

#import <Foundation/NSCoder.h>
@interface MyClass : NSObject <NSCoding> {…}

In my situation MyClass has two instance methods, one is of type NSDate and the other is integer. I want both of these to be persisted. So in MyClass.m I implement the two methods required by NSCoding as such,

-(void) encodeWithCoder: (NSCoder *) encoder
  [encoder encodeObject: myDateVarialbe];
  [encoder encodeObject: [NSNumber numberWithInteger:myIntegerVariable]];

-(id) initWithCoder: (NSCoder *) decoder
  myDateVariable = [[decoder decodeObject] retain];
  myIntegerVariable = [[[decoder decodeObject] retain] intValue];
  return self;

As you might have guessed, the first method gets called while encoding and the second while decoding. The array is now ready to be encoded.

NSMutableArray to NSData

NSData* myData = [NSKeyedArchiver archivedDataWithRootObject:myMutableArray];

NSData to NSMutableArray

NSMutableArray* myMutableArray = [NSKeyedUnarchiver unarchiveObjectWithData:myData];

Here I’m using NSKeyedArchiver and its counterpart NSKeyedUnarchiver. There are other archivers too. I chose NSKeyedArchiver because the documentation says it supports backward compatibility better.

5 thoughts on “NSMutableArray to NSData and NSData to NSMutableArray

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>