2

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?

Monolo
  • 18,205
  • 17
  • 69
  • 103
anna
  • 2,723
  • 4
  • 28
  • 37

1 Answers1

3

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];
Nicolas Bachschmidt
  • 6,475
  • 2
  • 26
  • 36
  • 1
    Awesome! I used the last suggestion. With a category I would still have to explicitly #import one the frameworks, which I wanted to avoid. Thanks. – anna Jul 11 '12 at 18:58