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

问题描述

objectForKey valueForKey 之间有什么区别?

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的许多教程。您还可以查看。

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之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:35