NSMutableDictionary 对每个值应用公式的最有效方法
我有一个带有 NSNumbers 的 NSMutableDictionary。当我完成构建集时,我需要使用当前存储的值本身重新计算所有值。现在我正在使用快速枚举并存储到一个新的 NSMutableSet 中,但我在 Objective C 方面没有经验,必须有一种更有效的方法来做到这一点:
for (id key in temp_target_results)
{
formula_score = MyFormula([[temp_target_results objectForKey:key] doubleValue]);
[target_results setObject:[NSNumber numberWithDouble:formula_score] forKey:key];
}
最后我按值排序(这就是为什么我使用 NSMutableSet)。
I have a NSMutableDictionary with NSNumbers. When I finish building the set I need to recalculate all the values using the currently stored value itself. Now I'm using fast enumeration and storing into a new NSMutableSet, but I'm not experienced in Objective C and there must be a more efficient way to do this:
for (id key in temp_target_results)
{
formula_score = MyFormula([[temp_target_results objectForKey:key] doubleValue]);
[target_results setObject:[NSNumber numberWithDouble:formula_score] forKey:key];
}
In the end I'm sorting by value (that's why I'm using NSMutableSet).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道还有多少人可以帮助您优化正在做的事情,因为我不知道幕后发生了什么(在您上面粘贴的代码片段的上下文之外,或者您的内部到底发生了什么)
MyFormula
函数)。我的一个优化问题是:为什么你将所有内容存储为 NSNumber 对象而不是双精度数组?这样做的唯一优势(我目前可以看到)是,如果您将
NSNumber
对象以NSArray
、NSSet
或NSDictionary
被写入磁盘或在NSNotification
中传递。但我要做的一些事情包括摆脱对
objectForKey
的额外、不必要的调用:这里的另一个考虑因素:
您的
target_results
似乎不是NSMutableSet
因为您正在执行setObject:forKey:
的NSMutableDictionary
方法。如果target_results
确实是一个NSMutableSet
,您只需要调用:I don't know how much more anyone can help you optimize what you are doing because I don't know what's going on behind the scenes (outside of the context of the snippet of code you pasted above, or what's really going on inside your
MyFormula
function).One optimization question I have would be: why are you storing everything as
NSNumber
objects anyways and not an array ofdoubles
? The only advantage (that I can currently see) to doing that is if you're passing yourNSNumber
objects along in anNSArray
,NSSet
orNSDictionary
that gets written out to disk or passed along in anNSNotification
or.But some of the things I would do would include getting rid of that extra, unnecessary call to
objectForKey
:Another consideration here:
Your
target_results
appears to not be aNSMutableSet
because you are doing aNSMutableDictionary
method ofsetObject:forKey:
. Iftarget_results
really was aNSMutableSet
, you'd only need to call: