• iOS-setValue和setObject的区别


    在使用NSMutableDictionary的时候经常会使用setValue forKey 与setObject forKey,他们经常是可以相互使用的,代码中经常每一种的使用都有。

    1.先看看setValue :forKey的定义

    @interface NSMutableDictionary(NSKeyValueCoding)

    /*

    Send - setObject:forKey:to the receiver,unless the value is nil,in which case send - removeObject:forKey

    */

    - (void) setValue: (id) value forKey :(NSString *) key;

    @end

    扩展NSMutableDictionary的一个类别,上面注释的很清楚,发送setObject:forKey给接收者,也就是调用setObject:forKey方法

    除非:value为nil的时候,调用removeObject:forKey

    2.在看看setObject:forKey的定义

    @interface NSMutableDictionary :NSDictionary

    - (void) removeObjectForKey :(id) akey;

    - (void) setObject :(id)anObject forKey:(id <NSCopying>)aKey;

    @end

    注意:setObject:forKey:中key对象是一个id类型,并不是NSString,只不过我们经常使用NSString而已。

    3.区分

    (1).[imageDictionary setObject : [NSNullnull] forKey;indexNumber];

    [NSNull null]表示的是一个空对象,并不是nil,注意这点

    (2).setObject:forKey:中key是NSNumber对象的时候,如下:

    [imageDictionary setObject:obj forKey:[NSNumber numberWithInt: 10]];

    4.注意

    上面说的区别是针对调用者是dictionary而言的

    setObject : forKey : 方法NSMutabledictionary特有的,而setValue :forKey 方法是KVC(键值编码)的主要方法。

    当setValue :forKey方法调用者是对象的时候

    setValue :forKey :方法是在NSObject对象中创建的,也就是说所有的oc对象都有这个方法,所以比如使用:

    SomeClass *someObj = [[SomeClass alloc] init];

    [someObj setValue :self forKey :@"delegate"];

    表示的意思是:对象someObj设置他的delegate属性的值为当前类,当前调用此方法的对象必须要有delegate属性。

  • 相关阅读:
    关于工作态度
    ajax请求链接加时间戳
    自动消失的提示效果
    表设计原则
    进度展示图
    freemarker时间格式化
    Java的Thread.currentThread().getName() 和 this.getName() 以及 对象.getName()区别???
    使用Github做服务器展示前端页面
    Spring的生命周期
    输入三个字符,从小到大的顺序输出这三个字符
  • 原文地址:https://www.cnblogs.com/zhoulina/p/5499663.html
Copyright © 2020-2023  润新知