本文介绍了保存自定义对象的NSArrays的NSDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本包含nsarrays的字典(如果有区别,它是可变的),而后者又包含了(NSObject的子类)我已经像这样实现了initWithCoder和encodeWithCoder:

I have a dictionary (it's mutable if that makes a difference) which contains nsarrays, which in turn contain (subclass of NSObject)sI have implemented initWithCoder and encodeWithCoder like this:

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    self.Title = [aDecoder decodeObjectForKey:@"Title"];
    self.SiteAPIURL = [aDecoder decodeObjectForKey:@"SiteAPIURL"];
    self.ID = [aDecoder decodeObjectForKey:@"ID"];
    return self;
}

-(void) encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.Title forKey:@"Title"];
    [aCoder encodeObject:self.SiteAPIURL forKey:@"SiteAPIURL"];
    [aCoder encodeObject:self.ID forKey:@"ID"];
}

但是当我执行[dictionary writeToFile:savepath atomically:YES];时,它无法正确保存那么我在做什么错了,什么是序列化?我需要使用NSKeyedArchiver还是什么?

But it doesn't save properly when I do [dictionary writeToFile:savepath atomically:YES];So what am I doing wrong, and what exactly is serialization and do I need I need to use NSKeyedArchiver or something?

推荐答案

[NSDictionary writeToFile: atomically:]使用NSPropertyListSerialization,它只能记录原始对象的子集(数字,字符串,日期和数据).因此,虽然可以将NSCodingNSKeyedArchiver一起用于归档对象,但是另一个选择是将对象编组为字符串或数据表示形式,将 that 存储在属性列表中,然后再次将其解编组加载时.

[NSDictionary writeToFile: atomically:] uses NSPropertyListSerialization, which can only record a subset of primitive objects (numbers, strings, dates and data). So while you could use NSCoding along with NSKeyedArchiver to archive the objects, another option is to marshal your objects into a string or data representation, store that in the property list, and unmarshal them again on loading.

这篇关于保存自定义对象的NSArrays的NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 23:13