On 06/11/2009, at 11:02 AM, Jon Nall wrote:

I have a helper function that encodes the component float values and then the decoder creates a CGColorRef back from those.

+(void)encodeColor:(CGColorRef)theColor
        withCoder:(NSCoder*)encoder
          withKey:(NSString*)theKey
{
   if(theColor != nil)
   {
       const CGFloat* components = CGColorGetComponents(theColor);
[encoder encodeFloat:components[0] forKey:[NSString stringWithFormat:@"%[email protected]", theKey]]; [encoder encodeFloat:components[1] forKey:[NSString stringWithFormat:@"%[email protected]", theKey]]; [encoder encodeFloat:components[2] forKey:[NSString stringWithFormat:@"%[email protected]", theKey]]; [encoder encodeFloat:components[3] forKey:[NSString stringWithFormat:@"%[email protected]", theKey]];
   }
   else
   {
       // Encode nil as NSNull
       [encoder encodeObject:[NSNull null] forKey:theKey];
   }
}


I'm still pretty new at this, though, so maybe others will know a better way.


A slightly better way would be to extend NSCoder using a category, then you can use it just as you would any other encode/decode method:

@interface NSCoder (CGColorRefCoding)

- (void)        encodeCGColorRef:(CGColorRef) ref forKey:(NSString*) key;
- (CGColorRef)  decodeCGColorRefForKey:(NSString*) key;

@end

You'd also have to store the colour space, number of components, pattern and so on. It would probably be better to convert this internally to an NSColor which supports NSCoding in order to deal with this rather than assuming that it's a 4-component RGB colour as you have here. Unfortunately NSColor and CGColorRef are not toll-free bridged, and converting from one to the other can be pretty tricky to cover all the possible variations. If you can use NSColor instead of CGColorRef in your app, so much the better.

--Graham


_______________________________________________

Cocoa-dev mailing list ([email protected])

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to