2
我有一堂課我想分享Cocoa和Cocoa Touch應用程序。本課程計算各種CGPoint
,並將它們存儲在一個數組中。在可可有[NSValue valueWithPoint]
。在Cocoa Touch中有[NSValue valueWithCGPoint]
。在Cocoa和Cocoa Touch的NSArray中存儲CGPoint的通用解決方案?
有沒有什麼解決方案可以讓我繞過這些框架特定的方法?
我有一堂課我想分享Cocoa和Cocoa Touch應用程序。本課程計算各種CGPoint
,並將它們存儲在一個數組中。在可可有[NSValue valueWithPoint]
。在Cocoa Touch中有[NSValue valueWithCGPoint]
。在Cocoa和Cocoa Touch的NSArray中存儲CGPoint的通用解決方案?
有沒有什麼解決方案可以讓我繞過這些框架特定的方法?
您可以在NSValue
上創建一個類別,以便將valueWithCGPoint:
和CGPointValue
方法添加到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
或者你可以使用valueWithBytes:objCType:
和getValue:
。
CGPoint point = {10, 10}; NSValue *value = [NSValue valueWithBytes:&point objCType:@encode(CGPoint)]; // ... [value getValue:&point];
太棒了!我使用了最後一個建議。對於一個類別,我仍然必須明確地#導入一個我想避免的框架。謝謝。 – anna 2012-07-11 18:58:43
不客氣。 – 2012-07-11 18:59:09