objective-c - objectForKey 和 valueForKey 的区别?

标签 objective-c cocoa key-value-coding

objectForKeyvalueForKey 有什么区别? 我在文档中查找了两者,它们对我来说似乎相同。

最佳答案

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

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

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 的知识,如果你在 Google 上特别是在 Scott Stevenson's blog 上有很多教程。 .您也可以查看NSKeyValueCoding Protocol Reference .

希望对您有所帮助。

关于objective-c - objectForKey 和 valueForKey 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1062183/

相关文章:

ios - Objective-C iOS 开发在设置变量时使用 viewDidLoad 或 initWithCoder,为什么?

objective-c - NSColor RGB颜色计算

macos - LLDB - 退出...退出?

objective-c - 为什么 NSDictionary 在我们的键中有 @ 符号时会崩溃?

cocoa - Interface Builder > Inspector > Bindings 中的 "Controller Key"是什么意思?

ios - UICollectionView 在 UICollectionViewCells 上调用 setNeedsDisplay

ios - 框架在自动生成的 swift 文件中不可见

objective-c - 在 NSPredicates 中使用关键路径

iOS:使用滚动功能显示图像和长文本的正确方法

objective-c - Apple Headers 包含多个类别