objectForKey
和 valueForKey
有什么区别?
我在文档中查找了两者,它们对我来说似乎相同。
最佳答案
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/