Friday, May 3, 2013

NSKeyedUnarchiver unarchiveObjectWithData example ios


Decodes and returns the object graph previously encoded by NSKeyedArchiver and stored in a given NSData object.
+ (id)unarchiveObjectWithData:(NSData *)data
Parameters of [NSKeyedUnarchiver unarchiveObjectWithData]
An object graph previously encoded by NSKeyedArchiver.
Return Value
The object graph previously encoded by NSKeyedArchiver and stored in data.
This method raises an NSInvalidArchiveOperationException if data is not a valid archive.
Example of [NSKeyedUnarchiver unarchiveObjectWithData]
NSMutableData *data = [NSMutableData data];
for (uint32_t i = 0; i < 1024 * 1024; ++i)
    [data appendBytes:&i length:sizeof(uint32_t)];

NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:[NSMutableArray arrayWithObject:data]];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:archive];

assert([data isEqual:[array lastObject]]);
Example of [NSKeyedUnarchiver unarchiveObjectWithData]
- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError {
    NSMutableArray *array = nil;
    NSLog(@"data is %@", data);

    @try {
        array = [NSKeyedUnarchiver unarchiveObjectWithData:data]; // line of the EXC_BAD_ACCESS
    @catch (NSException * e) {
        if (outError) {
            NSDictionary *d = [NSDictionary dictionaryWithObject:@"The data is corrupted." forKey:NSLocalizedFailureReasonErrorKey];
            *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:d];
        return NO;
    [self setEmployees:array];
    return YES;