2011-04-19 94 views
0

我需要向plist添加多个字典。怎么办?如何将字典添加到plist字典中?

NSMutableDictionary *rootDict = [[[NSMutableDictionary alloc] init] autorelease]; 
NSMutableDictionary *rowsDict = [[[NSMutableDictionary alloc] init] autorelease]; 
NSMutableDictionary *itemZeroDict1 = [[[NSMutableDictionary alloc] init] autorelease]; 

我需要添加rowsDictitemZeroDict1rootDict

+0

发布您在.plist中创建或阅读的代码。然后人们可以告诉你如何添加字典。 – 2011-04-19 14:25:01

+1

请用相关代码编辑您的问题,不要将其作为评论发布。 – Juliet 2011-04-19 14:28:37

+1

在未来,也[正确地设置你的代码格式](http://stackoverflow.com/editing-help)。谢谢! – 2011-04-19 14:32:48

回答

0
NSDictionary *root = [[NSDictionary alloc] initWithObjectsAndKeys: 
         [NSDictionary dictionaryWithObject:@"1" forKey:@"number"], 
         [NSDictionary dictionaryWithObject:@"2" forKey:@"number"], 
         nil]; 

NSString *error = nil; 
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:root 
                   format:NSPropertyListBinaryFormat_v1_0 
                errorDescription:&error]; 
if (plistData == nil) 
    NSLog(@"Error serializing plist: %@", error); 
else 
    // Do whatever you want with plistData 
[error release]; // this is an exception to the usual memory management in Cocoa 
0

使用下面的代码将字典写入.plist文件。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                  NSUserDomainMask, 
                  YES); 
     NSString *plistPath = [[paths lastObject] stringByAppendingPathComponent:@"friendList.plist"]; 

/* Code to remove Existing file from Document directory */ 

     if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath]){ 
      [[NSFileManager defaultManager] removeItemAtPath:plistPath error:nil]; 
     } 
//////////////// 

     /** Copy Plist file from your bundle resource to Document directory */ 

     NSString *bundle = [[NSBundle mainBundle] pathForResource:@"friendList" ofType:@"plist"]; 
     BOOL sucesss = [[NSFileManager defaultManager] copyItemAtPath:bundle toPath:plistPath error:nil]; 
     if (!sucesss) { 

     } 

     NSMutableArray *arryDict = [[NSMutableArray alloc] init]; 

     for (NSDictionary *dict in arryOfDictionary) { 

      NSDictionary *dictFriend = @{@"key":@"value"}; 

      [arryDict addObject:dictFriend]; 
     } 

     [arryDict writeToFile:plistPath atomically:NO];