Encoding CGPoint struct with NSCoder

后端 未结 3 955
别跟我提以往
别跟我提以往 2021-02-07 10:19

How do you encode and decode a CGPoint struct using NSCoder?

相关标签:
3条回答
  • 2021-02-07 10:36

    To encode:

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

    To decode:

    NSValue *decodedValue = [decoder decodeObjectForKey:@"point"];
    CGPoint point;
    [decodedValue getValue:&point];
    
    0 讨论(0)
  • 2021-02-07 10:47

    Just an update for iOS developers. You can do the following in Cocoa Touch (but not in Cocoa):

    [coder encodeCGPoint:myPoint forKey:@"myPoint"];
    
    0 讨论(0)
  • 2021-02-07 10:50

    CGPoints and NSPoints are both structures composed of two CGFloat values, so you can freely pass them around as each other. The quick and dirty way would be:

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

    This will usually work, but it technically breaks the C99 strict aliasing rules. If you want to be 100% compatible with the standard, you'll have to do something like:

    typedef union
    {
      CGPoint cgPoint;
      NSPoint nsPoint;
    } CGNSPoint;
    
    CGNSPoint cgnsPoint = { .cgPoint = myPoint };
    [myNSCoder encodePoint:cgnsPoint.nsPoint];
    
    0 讨论(0)
提交回复
热议问题