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:属性名(用于复合路径)

 

posted @ 2016-07-21 17:17  妮妮1018  阅读(3807)  评论(0编辑  收藏  举报