What is the difference between objectForKey and valueForKey?

本文详细解释了KVC(键值编码)中的valueForKey方法与NSDictionary类中objectForKey方法的区别。前者作为通用方法,允许通过字符串访问实例变量;后者则是针对字典类的方法,用于通过键获取字典中的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

--------------------------------------------------------------------------------------------------------------------------------------------------

A: "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 2 objects can have the same key (just as no 2 objects in an NSArray can have the same index).

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

NSNumber *anAccountNumber = [NSNumber numberWithInt:12345]; Account *newAccount = [[Account alloc] init]; [newAccount setAccountNumber:anAccountNUmber]; NSNumber *anotherAccountNumber = [newAccount accountNumber];

Using KVC, I can also do it like this:

NSNumber *anAccountNumber = [NSNumber numberWithInt:12345]; Account *newAccount = [[Account alloc] init]; [newAccount setValue:anAccountNumber forKey:@"accountNumber"]; NSNumber *anotherAccountNumber = [newAccount valueForKey:@"accountNumber"];

Those are equivalent sets of statements.

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).

If you want to learn more about KVC, there are many tutorials if you Google especially at Scott Stevenson's blog.

Hope that helps.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值