objectForKey 和 valueForKey 之间的区别?

2024-03-14

有什么区别objectForKey and valueForKey? 我在文档中查找了它们,它们对我来说似乎是一样的。


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

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

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

[newAccount setAccountNumber:anAccountNUmber];

NSNumber *anotherAccountNumber = [newAccount accountNumber];

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

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

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

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

这些是等效的语句集。

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

如果你想了解更多关于 KVC 的知识,如果你谷歌一下,有很多教程,特别是在斯科特·史蒂文森的博客 http://theocacao.com/。您还可以查看NSKeyValueCoding 协议参考 https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSKeyValueCoding_Protocol/Reference/Reference.html.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

objectForKey 和 valueForKey 之间的区别? 的相关文章

随机推荐