Friday, May 3, 2013

NSKeyedUnarchiver unarchiveObjectWithFile example ios


unarchiveObjectWithFile:

Decodes and returns the object graph previously encoded by NSKeyedArchiver written to the file at a given path.
+ (id)unarchiveObjectWithFile:(NSString *)path
Parameters of [NSKeyedUnarchiver unarchiveObjectWithFile]
path
A path to a file that contains an object graph previously encoded by NSKeyedArchiver.
Return Value of [NSKeyedUnarchiver unarchiveObjectWithFile]
The object graph previously encoded by NSKeyedArchiver written to the file path. Returnsnil if there is no file at path.
Discussion
This method raises an NSInvalidArgumentException if the file at path does not contain a valid archive.
Example of [NSKeyedUnarchiver unarchiveObjectWithFile]
- (NSMutableArray *)loadGame {
    NSString *gameDataPath = [self pathForFile:@"gameData.plist"];
    if([[NSFileManager defaultManager] fileExistsAtPath:gameDataPath]) {
        return [NSKeyedUnarchiver unarchiveObjectWithFile:gameDataPath];
    }
    return nil;
}
Example of [NSKeyedUnarchiver unarchiveObjectWithFile]
BOOL isFileExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
NSAssert(isFileExist, @"filePath does not exist");
NSKeyedUnarchiver* coder =
    [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; // nil
NSData* data = [[NSFileManager defaultManager] contentsAtPath:filePath];
coder = [NSKeyedUnarchiver unarchiveObjectWithData:data]; // nil
coder = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; // OK!!!