使用NSCoder编码CGPoint结构

时间:2009-01-15 19:40:58

标签: cocoa

如何使用NSCoder对CGPoint结构进行编码和解码?

3 个答案:

答案 0 :(得分:26)

编码:

CGPoint point = /* point from somewhere */
NSValue *pointValue = [NSValue value:&point withObjCType:@encode(CGPoint)];
[coder encodeObject:pointValue forKey:@"point"];

解码:

NSValue *decodedValue = [decoder decodeObjectForKey:@"point"];
CGPoint point;
[decodedValue getValue:&point];

答案 1 :(得分:16)

只是iOS开发人员的更新。您可以在Cocoa Touch中执行以下操作(但不在Cocoa中):

[coder encodeCGPoint:myPoint forKey:@"myPoint"];

答案 2 :(得分:10)

CGPointNSPoint s都是由两个CGFloat值组成的结构,因此您可以自由地将它们相互传递。快速而肮脏的方式是:

NSCoder *myNSCoder;
CGPoint myPoint;
[myNSCoder encodePoint:*(NSPoint *)myPoint];

这通常有效,但从技术上讲,它违反了C99严格的别名规则。如果您希望与标准100%兼容,则必须执行以下操作:

typedef union
{
  CGPoint cgPoint;
  NSPoint nsPoint;
} CGNSPoint;

CGNSPoint cgnsPoint = { .cgPoint = myPoint };
[myNSCoder encodePoint:cgnsPoint.nsPoint];