iPhone - Why does the documentation say UIImageView is NSCoding compliant?

这一生的挚爱 提交于 2019-11-28 18:55:40

The documentation is misleading -- UIImage does not conform to NSCoding as you've stated. You can work around it (in a primitive way) by doing the work yourself:

@interface UIImage (NSCoding)
- (id)initWithCoder:(NSCoder *)decoder;
- (void)encodeWithCoder:(NSCoder *)encoder;
@end

@implementation UIImage (NSCoding)
- (id)initWithCoder:(NSCoder *)decoder {
  NSData *pngData = [decoder decodeObjectForKey:@"PNGRepresentation"];
  [self autorelease];
  self = [[UIImage alloc] initWithData:pngData];
  return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
  [encoder encodeObject:UIImagePNGRepresentation(self) forKey:@"PNGRepresentation"];
}
@end
DougW

This question deserves an update since iOS 5.1 added functionality for NSCoding to UIImage, and Nathan de Vries answer will now cause warnings with the latest compilers.

This question offers a solution to work around the issue if your app supports iOS prior to 5.1. It does basically the same thing Nathan suggests, but checks whether the method already exists or not, rather than hard coding it.

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