乱世@小熊 2009-06-30 07:14 采纳率: 25%
浏览 222
已采纳

与 valueForKey 之间的区别?

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

转载于:https://stackoverflow.com/questions/1062183/difference-between-objectforkey-and-valueforkey

  • 写回答

4条回答 默认 最新

  • 关注

    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: 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];
    

    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"];
    

    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. You can also check out the NSKeyValueCoding Protocol Reference.

    Hope that helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求