Unarchive UIImage object returns CGSizeZero image using NSKeyedUnarchiver on iOS 8

邮差的信 提交于 2019-12-07 06:44:51

问题


I have this code working on iOS 7:

NSData *imageData = [NSKeyedArchiver archivedDataWithRootObject:self.imageView.image];
UIImage *imageCopy = [NSKeyedUnarchiver unarchiveObjectWithData:imageData];
NSLog(@"%@",NSStringFromCGSize(imageCopy.size));

but on iOS 8, imageCopy's size is always zero. Same thing happens when I archive UIImageView, the unarchived imageView's image has a zero size. I found out that in iOS 7, UIImage header is like:

UIImage : NSObject <NSSecureCoding, NSCoding>

but on iOS 8 it is :

UIImage : NSObject <NSSecureCoding>

It looks like the NSCoding protocol is missing on iOS 8. I have to encode the actual image data: UIImagePNGRepresentation(self.imageView.image) instead of the image to make sure I get a good image back.

Does anyone know why this happens? Is it for backward compatibility? I noticed in iOS earlier version UIImage doesn't conform to NSCoding.


回答1:


UIImage : NSObject <NSSecureCoding> is not a problem because NSSecureCoding inherits NSCoding.

Anyway, I confirmed the problem can be reproduced with following code:

UIImage *img = [UIImage imageNamed: @"myImage"];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:img];
UIImage *imgCopy = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"%@, %@", imgCopy, NSStringFromCGSize(imgCopy.size)); // -> (null), {0, 0}

On the other hand, the following code works as expected:

UIImage *img = [UIImage imageNamed: @"myImage"];
UIImage *img2 = [UIImage imageWithCGImage:img.CGImage scale:img.scale orientation:img.imageOrientation];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:img2];
UIImage *imgCopy = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"%@, %@", imgCopy, NSStringFromCGSize(imgCopy.size)); // -> <UIImage: 0x7fa013e766f0>, {50, 53}

I don't know why, maybe bug?

I think, this is related to imageAsset or traitCollection property introduced in iOS8



来源:https://stackoverflow.com/questions/26213575/unarchive-uiimage-object-returns-cgsizezero-image-using-nskeyedunarchiver-on-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!