Search code examples
iosobjective-cnskeyedunarchiver

How to deal with unarchiver with this situation..?


I'm making simple program that can archive my object and unarchive it when launching.

I have a lists.m where mutable array called favouritesList get store into file using archive. Inside list, i have simple object called favouriteItem

So, the problem happens with this code

-(void) loadList
{

self.favouritesList =
[[NSKeyedUnarchiver unarchiveObjectWithFile:self.fileName] mutableCopy];
if(self.favouritesList == nil)
    self.favouritesList = [[NSMutableArray alloc]init]; 

}

The exception that i've got is this [NSKeyedUnarchiver initForReadingWithData:]: incomprehensible archive (0x62, 0x70, 0x6c, 0x69, 0x73, 0x74, 0x30, 0x30)'

i know i'm unarchiving with file that is empty (actually it gets copied from the file from bundle which is also empty).

So, how can i avoid this when i still want my app to load data from file when launching. When i used as following code

-(void) loadData {
    self.URLLists = [NSMutableArray arrayWithContentsOfFile:self.path];
    if(self.URLLists == nil) {
     self.URLLists = [[NSMutableArray alloc]init];
    }

}

Here, even though the file at self.path was empty, it return nil and i can just say if it returned nil, i will assign new one for the first time. But, with NSkeyedUnarchiver it works a bit differently.. could you explain how it is different and how can i avoid this error..? Thank you.


Solution

  • The easier way out is to use exception handling:

    @try {
                self.favouritesList =
    [[NSKeyedUnarchiver unarchiveObjectWithFile:self.fileName] mutableCopy];
         }
         @catch ( NSException *e ) {
                self.favouritesList = [[NSMutableArray alloc]init]; // add more code as needed
         }
    

    Apple's documentation is here.

    https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Exceptions/Tasks/HandlingExceptions.html#//apple_ref/doc/uid/20000059-BBCHGJIJ