5

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.

KPM
  • 10,558
  • 3
  • 45
  • 66
gabbler
  • 13,626
  • 4
  • 32
  • 44

1 Answers1

7

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

rintaro
  • 51,423
  • 14
  • 131
  • 139
  • Really! I get the same result as yours,the other way worked, I firstly found the problem on imageView, after unarchiving, imageView copy's image size is zero,what do you think has caused that? The code in my question used self.imageView.image, the image is from cache, not from the resource bundle. – gabbler Oct 06 '14 at 11:38
  • Well, I have no idea, sorry :) – rintaro Oct 06 '14 at 12:12
  • i spend on it half of day. facepalm. AND ANSWER WORKS! – Andrey Gagan Mar 02 '15 at 14:35