gpt4 book ai didi

ios - 如何编码/解码具有自定义对象数组的自定义对象?

转载 作者:行者123 更新时间:2023-11-28 21:28:22 26 4
gpt4 key购买 nike

我有一个自定义对象,它有一个 property 和另一组自定义 NSDictionary 对象的 NSArray。当我对数组进行编码和解码时,NSDictionary 对象在应该具有值时却为空。我读过的所有内容都说 NSArray 对象符合 NSCoding,但我觉得我必须做更多的事情才能正确编码 NSDictionary NSArray 中的对象...我错过了什么?

@interface Game : NSObject <NSMutableCopying, NSCoding>
@property int rows;
@property int cols;
@property NSMutableArray *troughs;

- (void)encodeWithCoder:(NSCoder *)encoder {

// encoding properties
[encoder encodeInteger:rows forKey:@"rows"];
[encoder encodeInteger:cols forKey:@"cols"];
[encoder encodeObject:troughs forKey:@"troughs"];
}

- (id)initWithCoder:(NSCoder *)coder {
self = [super init];
if (self) {
rows = (int)[coder decodeIntegerForKey:@"rows"];
cols = (int)[coder decodeIntegerForKey:@"cols"];
troughs = [coder decodeObjectForKey:@"troughs"];
}
return self;
}

槽数组包含定义为的对象:

@interface Trough : NSDictionary <NSMutableCopying, NSCoding>
@property int col;
@property int row;
@property BOOL isLocked;
@property NSMutableArray *tokens;

- (void)encodeWithCoder:(NSCoder *)encoder {
// encoding properties
[encoder encodeInteger:col forKey:@"col"];
[encoder encodeInteger:row forKey:@"row"];
[encoder encodeBool:isLocked forKey:@"isLocked"];
[encoder encodeObject:tokens forKey:@"tokens"];
}

- (id)initWithCoder:(NSCoder *)coder {
self = [super init];
if (self) {
col = (int)[coder decodeIntegerForKey:@"col"];
row = (int)[coder decodeIntegerForKey:@"row"];
isLocked = [coder decodeBoolForKey:@"isLocked"];
tokens = [coder decodeObjectForKey:@"tokens"];
}
return self;
}

最佳答案

子类化 NSDictionary 非常不寻常。如果这些 NSCopying 实现有任何工作的机会,它们也需要调用继承的行为。

- (void)encodeWithCoder:(NSCoder *)aCoder {
[super encodeWithCoder:aCoder];
// encode your Trough properties
}

- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
// decode your trough properties
}
return self;
}

关于ios - 如何编码/解码具有自定义对象数组的自定义对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37265277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com