On Apr 28, 2010, at 04:28, Graham Cox wrote:

> Well, there is - (void)encodePoint:(NSPoint)point forKey:(NSString *)key, but 
> you can only use that from within a call to -encodeWithCoder:. If you have a 
> need to archive something from "outside", as in the OP's code, wrapping it in 
> a NSValue doesn't work (really, that seems to be an oversight on NSValue's 
> compliance with NSCoding), but converting it to a string will work. Same for 
> Rects, sizes et. al. I would think it's odds-on that the internals of 
> -encodePoint:forKey: just make a call to NSStringFromPoint anyhow.

I would really hope that the last statement *isn't* true. :) If my point's X 
and Y are not integral, using a string would in general not preserve the 
floating point values precisely.

As to the inability to archive NSValue-encoded structs, note that it's the 
archiver that's complaining, not the NSValue object. Keyed archivers don't 
support structs:

        
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Archiving/Tasks/codingctypes.html

So why would NSValue tell an archiver to encode its contents as a struct? 
Because the thing *is* a struct and that's all NSValue knows about it.

Instead of trying to solve this problem with strings, I use immutable, 
objectified versions of these structs, like this:

> @implementation MyPoint
> 
> @synthesize point;
> 
> - (id)initWithPoint:(NSPoint)initialPoint {
>       self = [super init];
>       if (!self)
>               return nil;
>       point = initialPoint;
>       return self;
> }
> 
> - (id) initWithCoder: (NSCoder*) coder {
>       self = [super init];
>       if (!self)
>               return nil;
>       point = [coder decodePointForKey: @"point"];
>       return self;
> }
> 
> - (void) encodeWithCoder: (NSCoder*) coder {
>       [coder encodePoint: point forKey: @"point"];
> }
> 
> - (NSUInteger)hash {
>       return point.x * point.y;
> }
> 
> - (BOOL)isEqual:(id)object {
>       if (!object)
>               return NO;
>       if (![object isKindOfClass:[self class]])
>               return NO;
>       MyPoint* otherPoint = object;
>       return NSEqualPoints (self.point, otherPoint.point);
> }


(I never bothered to go back and write a decent hash function.)


_______________________________________________

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