【iOS】Difference Between objectForKey and valueForKey in NSDictionary
来源:互联网 发布:国家税务总局网络大学 编辑:程序博客网 时间:2024/05/20 11:27
Difference Between objectForKey and valueForKey in NSDictionary
从 NSDictionary 取值的时候有两个方法,objectForKey:
和 valueForKey:
,这两个方法具体有什么不同呢?
先从 NSDictionary 文档中来看这两个方法的定义:
objectForKey: returns the value associated with aKey, or nil if no value is associated with aKey. 返回指定 key 的 value,若没有这个 key 返回 nil.
valueForKey: returns the value associated with a given key. 同样是返回指定 key 的 value。
直观上看这两个方法好像没有什么区别,但文档里 valueForKey:
有额外一点:
If key does not start with “@”, invokes objectForKey:. If key does start with “@”, strips the “@” and invokes [super valueForKey:] with the rest of the key. via Discussion
一般来说 key 可以是任意字符串组合,如果 key 不是以 @ 符号开头,这时候 valueForKey:
等同于 objectForKey:
,如果是以 @ 开头,去掉 key 里的 @ 然后用剩下部分作为 key 执行 [super valueForKey:]
。
比如:
这时候 value1
和 value2
是一样的结果。如果是这样一个 dict:
value1
可以正确取值,但是 value2
取值会直接 crash 掉,报错信息:
Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[<__NSCFDictionary 0x892fd80> valueForUndefinedKey:]: this class is not key value coding-compliant for the key theKey.’
这是因为 valueForKey:
是 KVC(NSKeyValueCoding)
的方法,在 KVC 里可以通过 property 同名字符串来获取对应的值。比如:
valueForKey:
取值是找和指定 key 同名的 property accessor,没有的时候执行 valueForUndefinedKey:
,而 valueForUndefinedKey:
的默认实现是抛出 NSUndefinedKeyException
异常。参考Getting Attribute Values Using Key-Value Coding
回过头来看刚才 crash 的例子, [dict valueForKey:@"@theKey"];
会把 key 里的 @ 去掉,也就变成了 [dict valueForKey:@"theKey"];
,而 dict 不存在 theKey
这样的 property,转而执行 [dict valueForUndefinedKey:@"theKey"];
,抛出 NSUndefinedKeyException
异常后 crash 掉。
objectForKey:
和 valueForKey:
在多数情况下都是一样的结果返回,但是如果 key 是以 @ 开头,valueForKey:
就成了一个大坑,建议在 NSDictionary 下只用 objectForKey:
来取值。
- Difference Between objectForKey and valueForKey in NSDictionary
- 【iOS】Difference Between objectForKey and valueForKey in NSDictionary
- What is the difference between objectForKey and valueForKey?
- NSDictionary: objectForKey: valueForKey:
- iOS开发中的objectForKey和valueForKey在NSDictionary中的区别
- ios开放--objectForKey与valueForKey在NSDictionary中的差异
- iOS积累--objectForKey与valueForKey在NSDictionary中的差异
- objectForKey与valueForKey在NSDictionary中的差异
- objectForKey与valueForKey在NSDictionary中的差异
- objectForKey与valueForKey在NSDictionary中的差异
- objectForKey与valueForKey在NSDictionary中的差异
- objectForKey与valueForKey在NSDictionary中的差异
- objectForKey与valueForKey在NSDictionary中的差异
- objectForKey与valueForKey在NSDictionary中的差异
- objectForKey与valueForKey在NSDictionary中的差异
- objectForKey与valueForKey在NSDictionary中的差异
- objectForKey与valueForKey在NSDictionary中的差异
- objectForKey与valueForKey在NSDictionary中的差异
- 使用图书馆的中国知网资源进行检索博硕士论文
- 迟到的ACM
- 编码风格-做一个会讲故事的程序员
- 前向算法
- c++ curl get 访问网页(post关于curl 的文章都有就不介绍了)
- 【iOS】Difference Between objectForKey and valueForKey in NSDictionary
- JAVA那些事
- 一道 i++ ++i 引起的整理
- 实现dos2linux功能-shell脚本篇
- 对话框详解2
- 利用onchang()事件一选中下拉框就提交值
- hdu 1162
- 注意 ExecuteNonQuery() 返回值 问题
- fstream打开文件模式