NSKeyedUnarchiver can't decode my string

261 views Asked by At

I am trying to make a document-based application where it needs to decode the content using NSKeyedUnarchiver. However, it failed to extract the information even though there is indeed data containing!

The following is my code, and also the debugging information! Please help! Thank you!

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

NSData* data = [fileWrapper regularFileContents];
NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
NSLog(@"contains %@? %@",preferredFilename,[unarchiver containsValueForKey:@"data"]?@"Yes":@"No");

NSString* decodedData = (NSString*)[unarchiver decodeObjectForKey:@"data"];
NSLog(@"Data For %@ Found %@",preferredFilename,decodedData);
return decodedData;
}


2013-12-10 15:57:27.802  contains note.data? Yes
2013-12-10 15:57:27.807  Data 1
2013-12-10 15:57:27.807  Data For note.data Found *nil description*

EDIT: This is how I encode my data.

- (void)encodeObject:(id<NSCoding>)object toWrappers:(NSMutableDictionary *)wrappers preferredFilename:(NSString *)preferredFilename{
NSMutableData* m_data = [NSMutableData data];
NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:m_data];
[archiver encodeObject:object forKey:@"data"];
[archiver finishEncoding];
NSFileWrapper* wrapper =[[NSFileWrapper alloc]initRegularFileWithContents:m_data];
[wrappers setObject:wrapper forKey:preferredFilename];
}
0

There are 0 answers