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属性。

 

posted on 2016-05-16 21:56  萌萌的周丽娜  阅读(303)  评论(0编辑  收藏  举报