Thursday, March 5, 2009

UIImage and NSCoding

Here is a category to conform UIImage to NSCoding so you can archive it. This is untested - I hacked this up a few minutes in response to a question posed on Twitter. Please let me know if it needs any corrections:

UIImage-NSCoding.h
//
// UIImage-NSCoding.h

#import <Foundation/Foundation.h>

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



UIImage-NSCoding.m
//
// UIImage-NSCoding.m

#import "UIImage-NSCoding.h"
#define kEncodingKey @"UIImage"

@implementation UIImage(NSCoding)
- (id)initWithCoder:(NSCoder *)decoder
{
if ((self = [super init]))
{
NSData *data = [decoder decodeObjectForKey:kEncodingKey];
self = [self initWithData:data];
}


return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder
{
NSData *data = UIImagePNGRepresentation(self);
[encoder encodeObject:data forKey:kEncodingKey];
}

@end



This is also checked into Google Code if you prefer to grab it from there.

No comments:

Post a Comment