You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 12:20:50