我需要将下面提到的keys
和values
(图像红色标记值)添加到propertylist
中。
需要的结构(需要在同一位置添加红色标记的键和值)
现在我的plist:
我的确切方案
JSON
解析器的数据。JSON
解析将数据存储到plist中,因为我使用了以下代码我正在使用的代码:
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);
}
答案 0 :(得分:0)
假设您的现有plist是由此代码创建的:
NSDictionary *dic = @{@"Planet":@"Earth",
@"Earth":@{@"1":@"Asia",
@"2":@"Africa"}
};
[dic writeToFile:path atomically:YES];
然后你需要在地球内插入一个新的键值对。
//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看起来像这样: