使用iOS在PropertyList中添加其他键和值

时间:2015-12-29 08:35:39

标签: ios objective-c xcode plist

我需要将下面提到的keysvalues(图像红色标记值)添加到propertylist中。

需要的结构(需要在同一位置添加红色标记的键和值)

description here

现在我的plist:

description here

我的确切方案

  1. 我创建了plist,并且我正在获取存储空间 来自JSON解析器的数据。
  2. 我有一个基于它的标准中介存储结构 存储(我在上面添加了图像二)
  3. 现在我需要添加两个布尔键和值 手动,进入plist。在哪里和哪个位置所有信息 我已经通过上面的图像标记并提到了一个。
  4. JSON解析将数据存储到plist中,因为我使用了以下代码
  5. 我正在使用的代码:

    NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
     NSDictionary *response = JSON[@"response"];
     NSArray *keys = [response allKeys];
    
     NSMutableArray *objects = [NSMutableArray new];
     for (NSString *key in keys) {
         NSMutableDictionary *object = response[key];
         NSPredicate *predicate = [NSPredicate predicateWithFormat:@"subject = %@",object[@"subject"]];
         NSArray *objectsWithSameSubject = [objects filteredArrayUsingPredicate:predicate];
         NSInteger subjects = [object[@"subject"] integerValue];
         if (subjects > 0) {
    
             NSMutableArray *Objects_Subjectcount = [NSMutableArray new];
             [object setObject:Objects_Subjectcount forKey:@"Objects_Subjectcount"];
             for (NSInteger i = 0; i < subjects; i++) {
                 [Objects_Subjectcount addObject:object];// object or anything you need
    
             }
         }
         [objects addObject:object];
     }
    
     NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
     NSString *documentsPath = paths.firstObject;
     NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"File.plist"];
     NSError *writeError = nil;
     NSDictionary *finalDict = @{@"Objects": objects};
     NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
     if(plistData){
         [plistData writeToFile:plistPath atomically:YES];
     }
     else {
         NSLog(@"Error in saveData: %@", error);
     }
    

1 个答案:

答案 0 :(得分:0)

假设您的现有plist是由此代码创建的:

NSDictionary *dic = @{@"Planet":@"Earth",
                      @"Earth":@{@"1":@"Asia",
                                 @"2":@"Africa"}
                      };

[dic writeToFile:path atomically:YES];

enter image description here

然后你需要在地球内插入一个新的键值对。

//read
NSDictionary *readDict = [NSDictionary dictionaryWithContentsOfFile:path];
//create a mutable dict to edit it
NSMutableDictionary *mDict = [readDict mutableCopy];
//read the key-value for earth, and we are gonna edit it
NSMutableDictionary *earthDict = mDict[@"Earth"];
//set new object, it can be anything, string, array, dictionary etc
[earthDict setObject:@{@"myName":@"Anoop"}
          forKey:@"new"];
//write it back to same file
[mDict writeToFile:path atomically:YES];

现在plist看起来像这样:

enter image description here