[Convert] the difference between setValue and setObject: setvaluesetobject
When using NSMutableDictionary, setValue forKey and setObject forKey are often used for interaction. Each type of code is often used.
1. Let's take a look at the definition of setValue: forKey :.
@ Interface NSMutableDictionary (NSKeyValueCoding)
/* Send-setObject: forKey: to the caller, unless the value is nil, in which case send-removeObject: forKey :.
*/
-(Void) setValue :( id) value forKey :( NSString *) key;
@ End
Extends the NSMutableDictionary class. The preceding annotation clearly states that setObject: forKey is sent to the receiver, that is, the setObject: forKey method is called.
Unless the value is nil, The removeObject: forKey method is called.
2. Check the definition of setObject: forKey :.
@ Interface NSMutableDictionary: NSDictionary
-(Void) removeObjectForKey :( id) aKey;
-(Void) setObject :( id) anObject forKey :( id <NSCopying>) aKey;
@ End
Note: The object in setObject: forKey: Is of the id type, not NSString, but NSString is often used.
The differences between the two are as follows:
1. The value in setObject: forkey: cannot be nil. Otherwise, an error is returned.
The value in setValue: forKey: Can be nil, but when the value is nil, The removeObject: forKey method is automatically called.
2. the parameter of setValue: forKey: can only be of the NSString type, while the parameter of setObject: forKey: can be of any type.
Note: setObject: forKey: the object cannot be stored in nil, which must be different from the following:
1, [imageDictionarysetObject: [NSNullnull] forKey: indexNumber];
[NSNull null] indicates an empty object, not nil. note this.
2. When the Key in setObject: forKey: is an NSNumber object, it is as follows:
[ImageDictionarysetObject: obj forKey: [NSNumber numberWithInt: 10];
Note:
The difference mentioned above is that the caller is a dictionary.
SetObject: forKey: unique to the NSMutabledictionary method, whereas
SetValue: forKey: the key-value encoding (KVC) method.
When setValue: forKey: The method caller is an object:
SetValue: forKey: The method is created in the NSObject object, that is, all oc objects have this method, so it can be used for any class.
For example:
SomeClass * someObj = [[SomeClass alloc] init];
[SomeObj setValue: self forKey: @ "delegate"];
Indicates that the value of the delegate attribute of the object someObj is set to the current class. Of course, the object that calls this method must have the delegate Attribute before it can be set. Otherwise, it will not work if it is called.