我发现很难写入/读取自定义对象数组。在我的应用程序中,Contact 类有一个 NSDictionary 作为属性,而这个字典有一个数组作为键的对象。我用NSCoder和NSKeyedArchiever序列化/反序列化我的对象,甚至尝试了 NSPropertyList序列化。一旦开始序列化 NSDictionary,我总是在序列化时出错。这是我的代码,我并没有真正找到关于如何序列化具有复杂结构的自定义对象的一般答案?
//Contact.m
//phoneNumbers is a NSDictionary
#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");
NSString *errorStr;
NSData *dataRep = [NSPropertyListSerialization dataFromPropertyList:self.phoneNumbers
format:NSPropertyListXMLFormat_v1_0
errorDescription:&errorStr];
NSLog(@"Data class %@", [dataRep class]);
if(!dataRep)
{
NSLog(@"Error encoding %@", errorStr);
}
[aCoder encodeObject:dataRep forKey:@"phones"];
NSLog(@"Encoding finished");
}
- (id) initWithCoder: (NSCoder *)coder
{
if (self = [super init])
{
[self setFirstName:[coder decodeObjectForKey:@"firstName"]];
[self setLastName:[coder decodeObjectForKey:@"lastName"]];
[self setAge:[coder decodeIntForKey:@"age"]];
NSString *errorStr;
NSData *data=[coder decodeObjectForKey:@"phones"];
NSDictionary *propertyList = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:&errorStr];
if(!propertyList)
{
NSLog(@"Error %@", errorStr);
}
[self setPhoneNumbers:propertyList];
}
return self;
}
//Serializing/Deserializing an array of Contact objects:
#pragma mark Import/Export
//Export Contacts to file
-(void)exportContactsToFile
{
BOOL done=[NSKeyedArchiver archiveRootObject:self.contacts toFile:[PathUtility getFilePath:@"phonebook"]];
NSLog(@"Export done: %i", done);
}
//Import Contacts from file
-(void)importContactsFromFile
{
self.contacts = [NSKeyedUnarchiver unarchiveObjectWithFile:[PathUtility getFilePath:@"phonebook"]];
}
有没有一种通用的好方法来序列化/反序列化objective-c中的对象?谢谢我得到的错误是:0objc_msgSend 1 CF_Retain ...这是堆栈跟踪,但我没有其他错误(