在使用NSMutableDictionary的時候經(jīng)常會使用setValue forKey與setObject forKey,他們經(jīng)常是可以交互使用的,代碼中經(jīng)常每一種的使用都有。
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的一個類別,上面注釋說的很清楚,發(fā)送setObject:forKey 給接收者,也就是調(diào)用setObject:forKey方法
除非value為nil的時候,調(diào)用方法removeObjectforKey:
2. 看看setObject:forKey:的定義####
@interface NSMutableDictionary :NSDictionary
- (void)removeObjectForKey:(id)aKey;
- (void)setObject:(id)anObject forKey:(id <NSCopying>)aKey;
@end
注意:setObject:forKey:中Key的對象是一個id類型,并不是NSString,只不過我們經(jīng)常使用NSString而已。
現(xiàn)在總結(jié)他們2者的區(qū)別就是:###
1. setObject:forkey:中value是不能夠為nil的,不然會報錯。####
setValue:forKey:中value能夠為nil,但是當value為nil的時候,會自動調(diào)用removeObject:forKey方法
2. setValue:forKey:中key的參數(shù)只能夠是NSString類型,而setObject:forKey:的可以是任何類型####
setObject:forKey:中Key是NSNumber對象的時候,如下:
[imageDictionarysetObject:obj forKey:[NSNumber numberWithInt:10]];
注意:setObject:forKey:對象不能存放nil要與下面的這種情況區(qū)分:####
[imageDictionarysetObject:[NSNullnull] forKey:indexNumber];
[NSNull null]表示的是一個空對象,并不是nil,注意這點
注意:###
上面說的區(qū)別是針對調(diào)用者是dictionary而言的。
setObject:forKey:方法NSMutabledictionary特有的,而
setValue:forKey:方法是KVC(鍵-值編碼)的主要方法。
當 setValue:forKey:方法調(diào)用者是對象的時候:
setValue:forKey:方法是在NSObject對象中創(chuàng)建的,也就是說所有的oc對象都有這個方法,所以可以用于任何類。
比如使用:
SomeClass *someObj = [[SomeClass alloc] init];
[someObj setValue:self forKey:@"delegate"];
表示的意思是:對象someObj設(shè)置他的delegate屬性的值為當前類,當然調(diào)用此方法的對象必須要有delegate屬性才能設(shè)置,不然調(diào)用了也沒效果
轉(zhuǎn)自: http://blog.csdn.net/itianyi/article/details/8661997