【发布时间】:2017-02-08 04:24:49
【问题描述】:
当我尝试使用 NSKeyedArchiver 对其进行编码和解码时,为什么这段代码 sn-p 中的 UIImage 没有恢复到其原始状态?
我希望“decodedImage”包含解码后的图像,但它只是 NULL。
// Any image here seems to repro the issue
UIImage *image = [UIImage imageNamed:@"soda.jpg"];
// This prints YES (1), just a sanity check.
NSLog(@"Confirms %d", [[UIImage class] conformsToProtocol:@protocol(NSCoding)]);
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *coder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[coder encodeObject:image forKey:@"image"];
[coder finishEncoding];
// I would expect this to be large, instead it's < 1kb.
NSLog(@"Data length is: %zu", (unsigned long)data.length);
NSKeyedUnarchiver *decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
// This prints YES (1)
NSLog(@"containsValueForKey returns %d", [decoder containsValueForKey:@"image"]);
// decodedImage is NULL here, even though containsValueForKey returned YES
UIImage *decodedImage = [decoder decodeObjectForKey:@"image"];
[decoder finishDecoding];
在这种情况下,我不是在寻找一种解决方法,比如先将 UIImage 转换为 NSData 并对其进行编码。原因是我试图重现一段不相关的代码,它使用了类似的东西,我试图理解它。
如果我首先通过 nsdata 往返图像并返回到 uiimage,代码会按预期工作,为什么??
UIImage *originalImage = [UIImage imageNamed:@"soda.jpg"];
NSData *imageData = UIImagePNGRepresentation(originalImage);
UIImage *image = [UIImage imageWithData:imageData];
【问题讨论】:
-
我认为这种怪异与使用 [UIImage imageNamed:] 创建的 UIImage 的序列化方式与其他 UIImage 不同,可能是因为它知道图像来自应用程序捆绑...
标签: ios objective-c uiimage