[轉]setValue和setObject的區別,setvaluesetobject
在使用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而已。
現在總結他們2者的區別就是:
1, setObject:forkey:中value是不能夠為nil的,不然會報錯。
setValue:forKey:中value能夠為nil,但是當value為nil的時候,會自動調用removeObject:forKey方法
2, setValue:forKey:中key的參數只能夠是NSString類型,而setObject:forKey:的可以是任何類型
注意:setObject:forKey:對象不能存放nil要與下面的這種情況區分:
1, [imageDictionarysetObject:[NSNullnull] forKey:indexNumber];
[NSNull null]表示的是一個Null 物件,並不是nil,注意這點
2, setObject:forKey:中Key是NSNumber對象的時候,如下:
[imageDictionarysetObject:obj forKey:[NSNumber numberWithInt:10]];
注意:
上面說的區別是針對調用者是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屬性才能設定,不然調用了也沒效果