如何用KVO与集合运算符对NSDictionary的NSNumber值求和(支持NSPredicate)
使用KVO集合运算符对NSDictionary的NSNumber值求和
核心解决方案
要对{ID: NSNumber}格式的字典所有值求和,直接使用KVO键路径allValues.@sum.self即可,该逻辑也能直接在NSPredicate中套用。
直接对字典实例求和验证
针对你给出的示例字典:
NSDictionary *sampleDict = @{ @"my_ID_abcd": @(8), @"my_ID_efgh": @(2), @"my_ID_ijkl": @(3) }; NSNumber *totalSum = [sampleDict valueForKeyPath:@"allValues.@sum.self"]; // totalSum的值为@13,完全符合预期
在NSPredicate中的应用场景
场景1:筛选包含字典属性的对象
假设你有一个类,其中包含目标字典属性:
@interface DataModel : NSObject @property (nonatomic, strong) NSDictionary *idValues; @end
要筛选idValues总和大于10的DataModel实例,谓词写法如下:
NSPredicate *sumFilterPredicate = [NSPredicate predicateWithFormat:@"idValues.allValues.@sum.self > %@", @10];
场景2:筛选字典数组中总和符合条件的元素
如果是直接对字典数组进行筛选,需要用SELF指代数组中的每个字典元素:
NSArray *dictCollection = @[sampleDict, @{@"key1": @(1), @"key2": @(2)}]; NSPredicate *arrayFilterPredicate = [NSPredicate predicateWithFormat:@"SELF.allValues.@sum.self > %@", @10]; NSArray *filteredDicts = [dictCollection filteredArrayUsingPredicate:arrayFilterPredicate]; // filteredDicts会包含你的示例字典sampleDict
常见问题排查
如果你之前尝试allValues.@sum.self未得到预期结果,大概率是以下原因:
- 字典中存在非NSNumber类型的值:确保所有值都是NSNumber实例,混合类型会触发KVO异常
- 谓词键路径层级错误:比如在数组筛选时遗漏
SELF,导致键路径解析失败
内容的提问来源于stack exchange,提问作者Thomas Albert
相关产品推荐
相关产品推荐

