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

前端 未结 2 611
南旧
南旧 2020-12-13 21:31

Ideally an NSCoding compliant class will work as expected using encodeWithCoder: and initWithCoder: (at least I thought so till recently) without the developer having to bot

相关标签:
2条回答
  • 2020-12-13 22:11

    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
    
    0 讨论(0)
  • 2020-12-13 22:20

    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.

    0 讨论(0)
提交回复
热议问题