anna
anna

Reputation: 2723

Universal solution for storing CGPoint in NSArray in Cocoa and Cocoa Touch?

I have a class that I would like to share between a Cocoa and Cocoa Touch applications. This class calculates various CGPoints and stores them in an array. In Cocoa there's [NSValue valueWithPoint]. In Cocoa Touch there's [NSValue valueWithCGPoint].

Is there any solution that would allow me to bypass using these framework-specific methods?

Upvotes: 2

Views: 232

Answers (1)

Nicolas Bachschmidt
Nicolas Bachschmidt

Reputation: 6505

You may create a category on NSValue in order to add the valueWithCGPoint: and CGPointValue methods to Cocoa.

#if ! TARGET_OS_IPHONE
@interface NSValue (MyCGPointAddition)
+ (NSValue *)valueWithCGPoint:(CGPoint)point;
- (CGPoint)CGPointValue;
@end
#endif
#if ! TARGET_OS_IPHONE
@implementation NSValue (MyCGPointAddition)
+ (NSValue *)valueWithCGPoint:(CGPoint)point {
    return [self valueWithPoint:NSPointFromCGPoint(point)];
}
- (CGPoint)CGPointValue {
    return NSPointToCGPoint([self pointValue]);
}
@end
#endif

Or you may use valueWithBytes:objCType: and getValue:.

CGPoint point = {10, 10};
NSValue *value = [NSValue valueWithBytes:&point objCType:@encode(CGPoint)];
// ...
[value getValue:&point];

Upvotes: 3

Related Questions