objectForKey 和 valueForKey 之间的区别? [英] Difference between objectForKey and valueForKey?

查看:17
本文介绍了objectForKey 和 valueForKey 之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

objectForKeyvalueForKey 有什么区别?我在文档中查找了两者,在我看来它们是一样的.

What is the difference between objectForKey and valueForKey? I looked both up in the documentation and they seemed the same to me.

推荐答案

objectForKey: 是一个 NSDictionary 方法.NSDictionary 是一个类似于 NSArray 的集合类,不同之处在于它不使用索引,而是使用键来区分项目.键是您提供的任意字符串.没有两个对象可以具有相同的键(就像 NSArray 中没有两个对象可以具有相同的索引一样).

objectForKey: is an NSDictionary method. An NSDictionary is a collection class similar to an NSArray, except instead of using indexes, it uses keys to differentiate between items. A key is an arbitrary string you provide. No two objects can have the same key (just as no two objects in an NSArray can have the same index).

valueForKey: 是一种 KVC 方法.它适用于任何类.valueForKey: 允许您使用字符串作为名称来访问属性.例如,如果我有一个带有 accountNumber 属性的 Account 类,我可以执行以下操作:

valueForKey: is a KVC method. It works with ANY class. valueForKey: allows you to access a property using a string for its name. So for instance, if I have an Account class with a property accountNumber, I can do the following:

NSNumber *anAccountNumber = [NSNumber numberWithInt:12345];
Account *newAccount = [[Account alloc] init];

[newAccount setAccountNumber:anAccountNUmber];

NSNumber *anotherAccountNumber = [newAccount accountNumber];

使用 KVC,我可以动态访问该属性:

Using KVC, I can access the property dynamically:

NSNumber *anAccountNumber = [NSNumber numberWithInt:12345];
Account *newAccount = [[Account alloc] init];

[newAccount setValue:anAccountNumber forKey:@"accountNumber"];

NSNumber *anotherAccountNumber = [newAccount valueForKey:@"accountNumber"];

这些是等效的语句集.

我知道你在想:哇,但讽刺的是.KVC 看起来不是那么有用.事实上,它看起来很罗嗦".但是,当您想在运行时进行更改时,您可以做很多在其他语言中困难得多的很酷的事情(但这超出了您的问题范围).

I know you're thinking: wow, but sarcastically. KVC doesn't look all that useful. In fact, it looks "wordy". But when you want to change things at runtime, you can do lots of cool things that are much more difficult in other languages (but this is beyond the scope of your question).

如果您想了解有关 KVC 的更多信息,可以在 Google 上找到很多教程,尤其是 Scott Stevenson 的博客.您还可以查看 NSKeyValueCoding 协议参考.

If you want to learn more about KVC, there are many tutorials if you Google especially at Scott Stevenson's blog. You can also check out the NSKeyValueCoding Protocol Reference.

希望有所帮助.

这篇关于objectForKey 和 valueForKey 之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆