zoukankan      html  css  js  c++  java
  • setObject:forKey:与setValue:forKey:的区别

    NSDictionary可以调起 setValue:forKey:、setValue:forKeyPath:,无法调起 setObject:forKey:。能调起的也不能真正的进行操作,这取决与不可变字典不可增删改的特性。

    NSMutableDictionary都可以调起

    然后看一下setObject:forKey: 、 setValue:forKey: 、 setValue:forKeyPath: 的标准调用语句:

    [muDict setValue:<#(nullable id)#> forKey:<#(nonnull NSString *)#>];
    [muDict setValue:<#(nullable id)#> forKeyPath:<#(nonnull NSString *)#>];
    [muDict setObject:<#(nonnull id)#> forKey:<#(nonnull id<NSCopying>)#>];

    明显可以看出:
    (1) setValue:forKey: 的value是可以为nil的(但是当value为nil的时候,会自动调用removeObject:forKey方法);
        setObject:forKey: 的value则不可以为nil。
    (2) setValue:forKey: 的key必须是不为nil的字符串类型;

       setObject:forKey: 的key可以是不为nil的所有类型。

    //Demo:
    NSMutableDictionary *dict   = [NSMutableDictionary dictionaryWithDictionary:@{@"cs":@"test"}];
    NSDictionary *testDict      = @{@"name"@"test_name"@"age"@"12"@"dict":dict};
    NSMutableDictionary *muDict = [NSMutableDictionary dictionaryWithDictionary:testDict];
    [muDict setObject:@"object" forKey:@"key"];
    [muDict setValue:@"value" forKey:@"key2"];
    //此时打印结果:
    {
        age = 12;
        dict =     {
            cs = test;
        };
        key = object;
        key2 = value;
        name = "test_name";
    }

    这里setObject:forKey:与setValue:forKey:的作用是相同的,先检测muDict中是否存在key对应的键值对,存在就直接替换原有的value,否者就插入一条新键值对。

    [muDict setValue:@"ceshi" forKeyPath:@"dict.cs"];
    NSLog(@"%@", muDict);
    //此时打印结果:
    {
        age = 12;
        dict =     {
            cs = ceshi;
        };
        key = object;
        key2 = value;
        name = "test_name";
    }

    这里是对muDict进行操作,处理复合路径dict.cs,首先检测muDict中是否存在dict对应的键值对,存在就去检测dict中是否有cs对应的键值对,有则替换value,没有创建键值对,如果muDict中检测不到dict的存在,那么就停止操作。

    setValue:forKey: 与 setValue:forKeyPath:
    动态设置: setValue:属性值 forKey:属性名(用于简单路径)、setValue:属性值 forKeyPath:属性路径(用于复合路径,例如Person有一个Account类型的属性,那么person.account就是一个复合属性)
    动态读取: valueForKey:属性名 、valueForKeyPath:属性名(用于复合路径)

  • 相关阅读:
    CVE-2018-18778 mini_httpd任意文件读取漏洞
    libssh 服务端权限认证绕过漏洞(CVE-2018-10933)
    Apache SSI 远程命令执行漏洞
    Weblogic < 10.3.6 'wls-wsat' XMLDecoder 反序列化漏洞(CVE-2017-10271)
    PHP-FPM 远程代码执行漏洞(CVE-2019-11043)
    msfvenom各平台payload生成
    msfvenom绕过杀软之stage编码
    msfvenom payload的可持续化
    metasploit几个重要的监听参数
    msfvenom参数简介
  • 原文地址:https://www.cnblogs.com/NINIiOS/p/5692500.html
Copyright © 2011-2022 走看看