iphone - NSCoding 和 ARC

标签 iphone ios objective-c automatic-ref-counting nscoding

我想存档我的自定义对象。 ClassA 拥有一个字典,其值是 ClassB 的实例。

ClassA 的 initWithCoder 一切看起来都很好,并且 _dictionary 被声明为 strong,但是在 init 返回并且我调用 callMeAfterInit 后,_dictionary 为空(不是 null,是一个有效的空字典) )。

这应该很简单,但我没有太多使用归档,所以也许我错过了一些基本的东西。什么可能导致 init 返回后字典被清空?

这是基本代码:

@interface ClassA : NSObject <NSCoding>
@property (strong, nonatomic) NSMutableDictionary *dictionary;
@end

@implementation ClassA

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

    [encoder encodeObject:self.dictionary forKey:@"dictionary"];
}

- (id)initWithCoder:(NSCoder *)decoder {

    self = [super init];
    if (self) {
        _dictionary = [decoder decodeObjectForKey:@"dictionary"];
        // breakpoint here and I can inspect a good dictionary, full of ClassB values
    }
    return self;
}

- (void)callMeAfterInit {

    NSLog(@"%@", self.dictionary);
    // Log output here shows an empty dictionary (valid, but with 0 pairs)
}

@end


@interface ClassB : NSObject <NSCoding>
@property (strong, nonatomic) NSNumber *number;
@property (strong, nonatomic) NSArray *array;
@end

@implementation ClassB

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

    [encoder encodeObject:self.number forKey:@"number"];
    [encoder encodeObject:self.array forKey:@"array"];
}

- (id)initWithCoder:(NSCoder *)decoder {

    self = [super init];
    if (self) {
        _number = [decoder decodeObjectForKey:@"number"];
        _array = [decoder decodeObjectForKey:@"array"];
    }
    return self;
}

@end

最佳答案

您没有显示调用 callMeAfterInit 的代码,因此这是猜测。

很可能,您没有与 ClassA 的同一个实例进行对话。您是否碰巧在某处调用了[[ClassA alloc] init];

关于iphone - NSCoding 和 ARC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17219633/

相关文章:

iphone - 将 NSMutableArray 保存到 Core Data

iphone - OpenGL ES iPhone - 绘制抗锯齿线

ios - 如何通过central模式向peripheral发送数据?

ios - 导航栏自行更改栏

ios - Objective C将项目添加到nsmutablearray返回nil

iphone - 外部化数据源以创建要在 iOS 应用程序上使用的内容

iphone - 在数组中存储指向结构的指针? iPhone

升级到 Xcode 4 和 iOS 4.3 后的 iPhone JSON 错误

iphone - 如何访问 UINavigationController 中的堆栈

iphone - ShareKit - 将链接图像发布到 facebook 墙上