如何使用NSCoder编码和解码CGPoint结构?
编码:
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];
只是iOS开发人员的更新.您可以在Cocoa Touch中执行以下操作(但不能在Cocoa中执行):
[coder encodeCGPoint:myPoint forKey:@"myPoint"];
CGPoint
s和NSPoint
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];