Search code examples
objective-cnskeyedarchivernskeyedunarchiver

Archiving Multiple Objects and Unarchiving them as array of objects in objective C


I am calling the function archiveQueue to store object of type MYJSON at various times through out the program, and now I want to restore everything that I stored uptill now in an array.

Following is the function that I am using to store the objects :

- (void)archiveQueue:(MYJSON *)msg{

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:msg];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *file = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"myqueue.txt"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager createFileAtPath:file contents:data attributes:nil];
    NSLog(@"ArchiveQueue: file = %@", file);

}

Following is the function I am using to restore the objects.

- (void)restoreQueue {


    NSLog(@"RestoreQueue: Restoring queue from Document Directory.");
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *file = [[paths objectAtIndex:0]  stringByAppendingPathComponent: @"myqueue.txt"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSData *data = [fileManager contentsAtPath:file];


        // How to unarchive that array of objects being stored. 

}

I want to know how should I unarchive everything I stored as an array of objects ?


Solution

  • In order to save a custom class with NSKeyedArchiver, that class needs to implement the NSCoding protocol. Even if instances of your class are included as members of an NSArray or NSDictionary you need to have them conform.

    Using createFileAtPath:contents:attributes: will overwrite the contents of that file.

    Here are some options:

    Archive an array of objects every time.

    get an array of all objects
    add your new object
    write that array to disk
    

    Archive objects to unique files in a directory

    documents/mySpecialObjects/A.myObject
    documents/mySpecialObjects/B.myObject
    documents/mySpecialObjects/C.myObject
    ...
    
    create local NSMutableArray
    enumerate all files inside of documents/mySpecialObjects
    unarchive each file and add to your array