Question

I usually encode my data in a NSFileWrapper like this (I leave out the NSFileWrapper bit):

-(NSData*)encodeObject:(id<NSCoding>)o {
        @autoreleasepool {            
            NSMutableData *data = [NSMutableData data];
            NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
            [archiver encodeObject:o forKey:@"data"];
            [archiver finishEncoding];
            return data;
        }
    }

And I usually get my data back when doing this:

- (id)decodeObjectFromWrapperWithPreferredFilename:(NSString *)p {

    NSFileWrapper *wrapper = [self.fileWrapper.fileWrappers objectForKey:p];
    if (!wrapper) {
        NSLog(@"Unexpected error: Couldn't find %@ in file wrapper!", p);
        return nil;
    }

    NSData *data = [wrapper regularFileContents];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

    NSLog(@"%@", [unarchiver decodeObjectForKey:@"data"]);
    return [unarchiver decodeObjectForKey:@"data"];

}

Sometimes, I get NSData back (it is not nil), but [unarchiver decodeObjectForKey:@"data"] will return NIL. It appears as if there is no object for the key @"data" even though there should be. I guess something must have gone wrong when encoding, but I'm not sure how to trouble shoot this. Can I just take whatever is in data and encode it, not worrying if it has got the right key? I mean there should only ever be one key "data".

Was it helpful?

Solution

Why is your code so complicated :) The NSKeyedArchiver class has helper methods that will do what you want more simply :

// to turn an object into NSData
return [NSKeyedArchiver archivedDataWithRootObject:o]; 

// To turn NSData into your object again
return [NSKeyedUnarchiver unarchiveObjectWithData:data];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top