The difference between setValue and setObject in iOS development

When using NSMutableDictionary, setValue forKey and setObject forKey are often used. They can often be used interactively, and each of them is often used in the code.

1, first look at the definition of 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

Extend a category of NSMutableDictionary, the above comment is very clear, send setObject:forKey to the receiver, that is, call the setObject:forKey method

Unless the value is nil, call the method removeObject:forKey


2, look at the definition of setObject: forKey:

@interface NSMutableDictionary :NSDictionary

- (void)removeObjectForKey:(id)aKey;

- (void)setObject:(id)anObject forKey:(id <NSCopying>)aKey;

@end

Note: The object of Key in setObject: forKey: is an id type, not NSString, but we often use NSString.


Now summarize the difference between the two of them:

1, setObject: forkey: The middle value cannot be nil, otherwise an error will be reported.

setValue: forKey: The value can be nil, but when the value is nil, the removeObject: forKey method will be called automatically

2, setValue: forKey: the key parameter can only be of type NSString, while setObject: forKey: can be of any type


Note: setObject: forKey: The object cannot be stored in nil to be distinguished from the following situation:

1, [imageDictionarysetObject:[NSNullnullforKey:indexNumber];

[ NSNull null ] means an empty object, not nil, pay attention to this 


2, setObject: forKey: When the Key is an NSNumber object, as follows:

    [imageDictionarysetObject:obj forKey:[NSNumber numberWithInt:10]];


note:

The difference mentioned above is for the caller is a dictionary.

setObject:forKey: method is unique to NSMutabledictionary, and

The setValue:forKey: method is the main method of KVC (key-value coding).


When the caller of the setValue:forKey: method is an object:

The setValue:forKey: method is created in the NSObject object, which means that all oc objects have this method, so it can be used in any class.

For example, use:

SomeClass *someObj = [[SomeClass alloc] init];

[someObj setValue:self forKey:@"delegate"];

It means: the object someObj sets the value of its delegate attribute to the current class, of course, the object calling this method must have the delegate attribute to set, otherwise the call will have no effect




This article is reproduced from: http://blog.csdn.net/itianyi/article/details/8661997


Guess you like

Origin blog.csdn.net/niumanxx/article/details/79649289