setObject:forKey:和setValue:forKey:在NSMutableDictionary中的区别在哪里?

编程入门 行业动态 更新时间:2024-10-11 21:22:01
本文介绍了setObject:forKey:和setValue:forKey:在NSMutableDictionary中的区别在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在查看文档时,我几乎看不到任何重大差异。 value和object都是id 类型,因此可以是任何对象。 Key一次是字符串,另一种情况是id。其中一个似乎保留了对象,而另一个则没有。还有什么?哪一个适用于哪种情况?

When looking at the documentation, I hardly see any big difference. Both "value" and "object" are of type id, so can be any object. Key is once a string, and in the other case an id. One of them seems to retain the object, and the other don't. What else? Which one is for what case?

推荐答案

setValue:forKey: is NSKeyValueCoding 协议的一部分,除此之外,还允许您从Interface Builder等访问对象属性。 setValue:forKey:在 NSDictionary 以外的类中实现。

setValue:forKey: is part of the NSKeyValueCoding protocol, which among other things, lets you access object properties from the likes of Interface Builder. setValue:forKey: is implemented in classes other than NSDictionary.

setObject:forKey:是 NSMutableDictionary的存在的原因。它的签名恰好与setValue:forKey:非常相似,但更通用(例如任何键类型)。签名非常相似,这有点巧合。

setObject:forKey: is NSMutableDictionary's reason to exist. Its signature happens to be quite similar to setValue:forKey:, but is more generic (e.g. any key type). It's somewhat of a coincidence that the signatures are so similar.

令人困惑的是,NSMutableDictionary的 setValue:forKey:相当于 setObject:forKey:。在其他类中, setValue:forKey:更改成员变量。在 NSMutableDictionary 中,它会更改字典条目,除非您在键前加上@字符 - 在这种情况下它会修改成员变量。

What adds to the confusion is that NSMutableDictionary's implementation of setValue:forKey: is equivalent to setObject:forKey: in most cases. In other classes, setValue:forKey: changes member variables. In NSMutableDictionary, it changes dictionary entries, unless you prefix the key with a '@' character -- in which case it modifies member variables.

因此,简而言之,当您需要使用字典键和值时,使用 setObject:forKey:,并且 setValue:forKey:在极少数情况下你需要解决 KVP 。

So, in a nutshell, use setObject:forKey: when you need to work with dictionary keys and values, and setValue:forKey: in the rarer cases where you need to tackle KVP.

编辑:哦,看起来这个问题已被问及之前回答: objectForKey和valueForKey之间的差异?

and oh, it looks like this has been asked and answered before: Difference between objectForKey and valueForKey?

更多推荐

setObject:forKey:和setValue:forKey:在NSMutableDictionary中的区别在哪里?

本文发布于:2023-11-14 22:06:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1588621.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   forKey   setObject   NSMutableDictionary   setValue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!