• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag
 

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: NSCoder and CGColorRef
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: NSCoder and CGColorRef


  • Subject: Re: NSCoder and CGColorRef
  • From: Graham Cox <email@hidden>
  • Date: Fri, 6 Nov 2009 12:55:29 +1100


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:@"%@.red", theKey]];
[encoder encodeFloat:components[1] forKey:[NSString stringWithFormat:@"%@.green", theKey]];
[encoder encodeFloat:components[2] forKey:[NSString stringWithFormat:@"%@.blue", theKey]];
[encoder encodeFloat:components[3] forKey:[NSString stringWithFormat:@"%@.alpha", 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@hidden)

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:
This email sent to email@hidden


References: 
 >NSCoder and CGColorRef (From: Alexander Cohen <email@hidden>)
 >Re: NSCoder and CGColorRef (From: Jon Nall <email@hidden>)

  • Prev by Date: Re: NSTreeController, Core Data and root objects
  • Next by Date: Re: PolKit for Leopard and later
  • Previous by thread: Re: NSCoder and CGColorRef
  • Next by thread: Re: NSCoder and CGColorRef
  • Index(es):
    • Date
    • Thread