Yuk*_*ora 7 objective-c nsdictionary uitableview ios
我正在开发一个iOS应用程序,我将从服务器获取一个JSON对象,它将填充在UITableView上.
用户可以在tableview上更改值,从而生成新的JSON.现在我想只将delta(两个JSON对象的差异)发送回服务器.我知道我可以遍历两个对象来寻找delta.但只是想知道这个问题是否有任何简单的解决方案.
例如:
NSDictionary *dict1 = {@"Name" : "John", @"Deptt" : @"IT"};
NSDictionary *dict2 = {@"Name" : "Mary", @"Deptt" : @"IT"};
Delta = {@"Name" : "Mary"}
Run Code Online (Sandbox Code Playgroud)
考虑到新的价值是玛丽的关键名称;
提前致谢
isEqualToDictionary: 返回一个布尔值,该值指示接收字典的内容是否等于另一个给定字典的内容。
if ([NSDictionary1 isEqualToDictionary:NSDictionary2) {
NSLog(@"The two dictionaries are equal.");
}
Run Code Online (Sandbox Code Playgroud)
如果两个字典各自拥有相同数量的条目,并且对于给定的键,每个字典中的对应值对象都满足isEqual:测试,则两个字典具有相同的内容。
以下是如何获取所有具有不匹配值的键。如何处理这些键是应用程序级别的问题,但信息最丰富的结构将包括来自两个字典的不匹配值的数组,以及处理来自另一个字典中不存在的键:
NSMutableDictionary *result = [@{} mutableCopy];
// notice that this will neglect keys in dict2 which are not in dict1
for (NSString *key in [dict1 allKeys]) {
id value1 = dict1[key];
id value2 = dict2[key];
if (![value1 equals:value2]) {
// since the values might be mismatched because value2 is nil
value2 = (value2)? value2 : [NSNull null];
result[key] = @[value1, value2];
}
}
// for keys in dict2 that we didn't check because they're not in dict1
NSMutableSet *set1 = [NSMutableSet setWithArray:[dict1 allKeys]];
NSMutableSet *set2 = [NSMutableSet setWithArray:[dict2 allKeys]];
[set2 minusSet:set1]
for (NSString *key in set2) {
result[key] = @[[NSNull null], dict2[key]];
}
Run Code Online (Sandbox Code Playgroud)
当然有更经济的方法可以做到这一点,但此代码针对指令进行了优化。
| 归档时间: |
|
| 查看次数: |
4168 次 |
| 最近记录: |