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
.
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