2012-09-04 87 views
0

這個問題似乎是一個副本,但事實並非如此。 我的聯絡類確認到NSCoding協議,實施方法:NSCoder編碼一個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"); 

    [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作爲屬性? 謝謝

回答

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 
} 
+0

但是回到NSDictionary? –

+0

NSDictionary * propertyList = [NSPropertyListSerialization propertyListFromData:dataRep mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:&errorStr]; if(!propertyList){ // Handle error } – prashant

+0

http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/Archiving/Articles/serializing.html – prashant