2

カスタム構造体を含むNSKeyedArchiverをエンコードするために を使用できる方法はありますか? ラップされた構造体を含むNSValueがあり、これをより大きなオブジェクト グラフの一部としてアーカイブしたいのですが、次のエラーが表示されます。NSDictionaryNSValues

-[NSKeyedArchiver encodeValueOfObjCType:at:]: this archiver cannot encode structs

ただし、次の点を考慮してください。

//Copy of the CGPoint declaration
struct MYPoint { 
    CGFloat x;
    CGFloat y;
};
typedef struct MYPoint MYPoint;

CGPoint point   = {1.0, 1.0};
MYPoint myPoint = {1.0, 1.0};

NSLog(@"CGPoint: %s", @encode(CGPoint)); //CGPoint: {CGPoint=ff}
NSLog(@"MYPoint: %s", @encode(MYPoint)); //MYPoint: {MYPoint=ff}

NSValue *CGPointValue = [NSValue valueWithBytes:&point objCType:@encode(CGPoint)];
NSData  *CGPointData  = [NSKeyedArchiver archivedDataWithRootObject:CGPointValue];
//NO ERROR    

NSValue *MYPointValue = [NSValue valueWithBytes:&myPoint objCType:@encode(MYPoint)];
NSData  *MYPointData  = [NSKeyedArchiver archivedDataWithRootObject:MYPointValue];
//ERROR: -[NSKeyedArchiver encodeValueOfObjCType:at:]: this archiver cannot encode structs

「このアーカイバはあなたの構造体をエンコードできません」というだけの場合で、それで話は終わりCGPointですか、それともカスタム構造体の場合と同じ動作をすることは可能ですか?

おそらく、それを回避するためにをラップしNSValueて実装する小さなカスタム オブジェクトを作成するだけですが、上記のコードに示されている矛盾に興味があり、同じ動作を得るために NSValue を拡張する方法があるかどうか疑問に思っています。NSCodingCGPoint

4

2 に答える 2

1

There are issues with something to do with @encode and anonymous structs. Try changing the struct definition to:

typedef struct MYPoint { 
    CGFloat x;
    CGFloat y;
} MYPoint;

If that doesn't work, you can wrap the struct using NSData:

[NSData dataWithBytes:&myPoint length:sizeof(MYPoint)];
于 2013-06-05T13:19:01.077 に答える