Search code examples
iphonenskeyedarchiver

About NSException from "NSKeyedUnarchiver unarchiveObjectWithFile :"


NSArray *t_annos;

@try 
{
  NSLog(@" --- pointer before = %ld --- ", (long) t_annos);  
  t_annos 
     = [NSKeyedUnarchiver unarchiveObjectWithFile : d_path]; 
  NSLog(@" --- pointer after  = %ld --- ", (long) t_annos);
}
@catch (NSException *e) 
{
  NSLog(@" --- e caught  ---"); 
  t_annos = nil;     
}

Please consider the above statements, the situation is :

1

According to documentation, an exception should be raised if d_path does not point to a valid archive. But no exception is caught even if d_path is deliberately set with an invalid path.

2

Have tested the code on both the xcode simulator and a test devise (iphone). Although both the simulator and the phone devise do not catch any exceptions, the phone unarchives the array as expected while on the simulator the program stops with an output : "Program received signal : "EXC_BAD_ACCESS"" at the Debugger Console.

3

The "bad access" error should have come at the "unarchiveObjectWithFile" statement since the program stops after the first NSLog output.

4

When try with a single NSString object archived and unarchive, both the simulator and the test device have no problem. But there is still no exception caught even when the path is wrong.

There may be something missing on my part, hope that somebody knowledgable can help.


Solution

  • According to the documentation, the exception is thrown only when there exists a file at the path and is not an archive created by NSKeyedArchiver.

    unarchiveObjectWithFile:

    Decodes and returns the object graph previously encoded by NSKeyedArchiver written to the file at a given path. + (id)unarchiveObjectWithFile:(NSString *)path

    Parameters: path

    A path to a file that contains an object graph previously encoded by NSKeyedArchiver.

    Return Value

    The object graph previously encoded by NSKeyedArchiver written to the file path. Returns nil if there is no file at path.

    Discussion

    This method raises an NSInvalidArgumentException if the file at path does not contain a valid archive.

    So, for -

    1: Most likely the invalid path that you set is not pointing to any file, and hence the return value is nil without any exception.

    2: Have you ensured the path on the simulator points to a valid file archived by NSKeyedArchiver earlier? Most likely, it points to some other file.

    4: Same thing as #1.