SetValue Forkey and SetObject forkey are often used when using nsmutabledictionary, and they can often be used interactively, often in every use of 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
Extension Nsmutabledictionary A category, the above comment is very clear, send setobject:forkey to the receiver, that is, call Setobject:forkey method
Unless value is nil, the method is called 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: Setobject:forkey: The object in key is an ID type, not a nsstring, but we often use nsstring.
Now the difference between the 2 of them is:
1, Setobject:forkey: In value is not able to nil, or will error.
Setvalue:forkey: Value can be nil, but when value is nil, the Removeobject:forkey method is called automatically
2, Setvalue:forkey: The parameter in key can only be nsstring type, and Setobject:forkey: can be any type
Note: Setobject:forkey: objects cannot hold nil to differentiate from this situation:
1, [Imagedictionarysetobject:[nsnullnull] forkey:indexnumber];
[NSNull null] represents an empty object, not nil, note this
2, Setobject:forkey: When key is the NSNumber object, the following:
[Imagedictionarysetobject:obj Forkey:[nsnumber numberwithint:10];
Attention:
The difference mentioned above is for the caller to be dictionary.
Setobject:forkey: Method Nsmutabledictionary Peculiar, and
Setvalue:forkey: Method is the Main method of KVC (key-value encoding).
When Setvalue:forkey: The method caller is an object:
Setvalue:forkey: The method is created in the NSObject object, which means that all OC objects have this method, so they can be used in any class.
For example, use:
SomeClass *someobj = [[SomeClass alloc] init];
[Someobj setvalue:self forkey:@ "Delegate"];
Object Someobj Set the value of his delegate property to the current class, and of course the object calling this method must have a delegate property to set, or the call will not be effective
The difference between SetObject and SetValue