I’ve been working on a side project at Shopify recently and one of the things I had to take a converted JSON object and store it on disk as a cache. I’m typically working with NSArrays and other fancy things so I figured this is where I’d look for serializing that data into a plist on disk.
-(BOOL) saveArray:(NSArray*)itemsArray toLocationOnDisk:(NSString*)location
{
BOOL saved = [itemsArray writeToFile:location atomically:YES];
return saved;
}
Because I’m targetting iOS 5 I have this nifty new tool available, it’s NSJSONSerialization though there’s a bit of a caveat. The data that you get back from it isn’t actually objects of NSArray, NSDictionary although for all intents and purposes they behave like they are in your code.
There is another way to get around this though, what you can do is convert the array into an archived object like so.
-(BOOL) saveArray:(NSArray*)itemsArray toLocationOnDisk:(NSString*)location
{
NSData *archivedItemsArray = [NSKeyedArchiver archivedDataWithRootObject:itemsArray];
BOOL saved = [archivedItemsArray writeToFile:location atomically:YES];
return saved;
}
Now all we need to do is re-convert that data into an NSArray, which is relatively straightforward.
// Deserialize the object back to an NSArray
-(NSArray*) getArrayFromDisk:(NSString*)location
{
NSData *rawData = [NSData dataWithContentsOfFile:location];
if(rawData == nil)
// Assuming iOS 5 using ARC
return [[NSArray alloc] init];
return (NSArray*) [NSKeyedUnarchiver unarchiveObjectWithData:rawData];
}
Once you know about this, it’s pretty straightforward but trying to find answers on sites like StackOverflow for this kind of problem is a bit tricky since people often assume you are working with plain old NSArrays and such.