Search code examples
iosnsmutablearraynsdataicloud

Save a NSArray to iCloud and retrieve it


I have an app that currently saves a NSMutableArray to a file in the documents directory on the iPad. This is saved by

[residentData writeToFile:filePath atomically:NO];

and is read back in by;

residentData = [[NSMutableArray alloc] initWithContentsOfFile:filePath];

I need to write this file to iCloud, as the data needs to be available across several devices. I have tried the following to create the file in iCloud;

NSData *myFileData = [NSKeyedArchiver archivedDataWithRootObject:residentData];
[fileManager createFileAtPath:[icloudURL path] contents:myFileData attributes:nil];

Which does indeed create a file in the correct place. I am struggling though to understand how to read this file back into my NSMutableArray (residentData). I have tried;

residentData = [NSKeyedUnarchiver unarchiveObjectWithData:myFileData];

But this doesn't decode into the array correctly. Please can someone show me the error of my ways - I suspect a fundamental misunderstanding on my part of NSData is to blame, but any pointers would be welcome.


Solution

  • It finally clicked, my approach was wrong. I don't need to use any of the above. Once I have done the;

     [fileManager setUbiquitous:YES itemAtURL:currentPlace destinationURL:icloudURL error:&error];
    

    The system takes care of everything else - i.e. just accessing the file normally with

    residentData = [[NSMutableArray alloc] initWithContentsOfURL:icloudURL];
    

    Has worked.