0

这个问题似乎是一个副本,但事实并非如此。我的 Contact 类确认 NSCoding 协议,实现方法:

#pragma mark Encoding/Decoding
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    NSLog(@"Encoding");
    [aCoder encodeObject:self.firstName forKey:@"firstName"];
    NSLog(@"First name encoded");
    [aCoder encodeObject:self.lastName forKey:@"lastName"];
    NSLog(@"Last name encoded");
    [aCoder encodeInt:self.age forKey:@"age"];
    NSLog(@"Age encoded");

    [aCoder encodeObject:self.phoneNumbers forKey:@"phoneNumbers"];


    NSLog(@"Encoding finished");

}


- (id) initWithCoder: (NSCoder *)coder
{
    if (self = [super init])
    {
        [self setFirstName:[coder decodeObjectForKey:@"firstName"]];
        [self setLastName:[coder decodeObjectForKey:@"lastName"]];
        [self setPhoneNumbers:[coder decodeObjectForKey:@"phoneNumbers"]];
        [self setAge:[coder decodeIntForKey:@"age"]];
    }
    return self;
}

PhoneNumbers 是一个字典,当编码达到对其进行编码时,应用程序崩溃。这就是我序列化联系人数组的方式:

#pragma mark Import/Export

//Export Contacts to file
-(void)exportContactsToFile
{
    BOOL done=[NSKeyedArchiver archiveRootObject:self.contacts toFile:[PathUtility getFilePath:@"phonebook"]];

}

//Import Contacts from file

-(void)importContactsFromFile
{
    self.contacts = [NSKeyedUnarchiver unarchiveObjectWithFile:[PathUtility getFilePath:@"phonebook"]];

}

我应该如何将 NSDictionary 序列化为属性?谢谢

4

1 回答 1

1

NSPropertyListSerialization 类提供了将属性列表对象与 XML 或优化的二进制格式相互转换的序列化方法。NSPropertyListSerialization 类对象提供了序列化过程的接口;您不创建 NSPropertyListSerialization 的实例。

NSDictionary *propertyList= @{ @"FirstNameKey" : @"Edmund",
                           @"LastNameKey" : @"Blackadder" };
NSString *errorStr;
NSData *dataRep = [NSPropertyListSerialization dataFromPropertyList:propertyList
            format:NSPropertyListXMLFormat_v1_0
            errorDescription:&errorStr];
if (!dataRep) {
// Handle error
}
于 2012-09-04T09:35:05.047 回答