Differences between setValue: forKey and setObject: forKey, objectForKey, and valueForKey in NSDictionary for IOS development

Source: Internet
Author: User

SetValue: forKey and setObject: forKey

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

Extended a category of NSMutableDictionary, which is clearly described in the above comment. Send setObject: forKey
To the receiver, that is, to call the setObject: forKey method.

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.

Differences between objectForKey and valueForKey

The NSDictionary has two methods: objectForKey: And valueForKey:. What are the differences between the two methods?

First, we can see the definitions of the two methods in the NSDictionary document:

ObjectForKey: returns the value associated with aKey, or nil if no value is associated with aKey. the value of the specified key is returned. if this key is not found, nil is returned.

ValueForKey: returns the value associated with a given key. Similarly, the value of the specified key is returned.

Intuitively, there seems to be no difference between the two methods, but valueForKey in this document:

If key does not start with "@", invokes objectForKey :. if key does start with "@", strips the "@" and invokes [super valueForKey:] with the rest of the key. via Discussion

In general, the key can be any string combination. If the key does not start with the @ symbol, then valueForKey: is equivalent to objectForKey:. If it starts, remove the @ in the key and use the remaining part as the key to execute [super valueForKey:].

For example:

NSDictionary * dict = [NSDictionary dictionaryWithObject: @ "theValue"

ForKey: @ "theKey"];

NSString * value1 = [dict objectForKey: @ "theKey"];

NSString * value2 = [dict valueForKey: @ "theKey"];

At this time, value1 and value2 are the same results. For such a dict:

NSDictionary * dict = [NSDictionary dictionaryWithObject: @ "theValue"

ForKey: @ "@ theKey"]; // note that this key starts @

NSString * value1 = [dict objectForKey: @ "@ theKey"];

NSString * value2 = [dict valueForKey: @ "@ theKey"];

The value of value1 is correct, but the value of value2 is crash directly. The error message is as follows:

Terminating app due to uncaught exception 'nsunknownkeyexception', reason: '[<__ NSCFDictionary 0x892fd80> valueForUndefinedKey:]: this class is not key value coding-compliant for the key theKey .'

This is because valueForKey: Is a KVC (NSKeyValueCoding) method. In KVC, you can use a string with the same name as property to obtain the corresponding value. For example:

@ Interface Person: NSObject

@ Property (nonatomic, retain) NSString * name;

@ End

...

Person * person = [[Person alloc] init];

Person. name = @ "fannheyward ";

NSLog (@ "name: % @", [person name]);

// Name: fannheyward

NSLog (@ "name: % @", [person valueForKey: @ "name"]);

// Name: fannheyward

[Person release];

ValueForKey: The value is the property accessor with the same name as the specified key. If no value is available, valueForUndefinedKey: is executed. The default Implementation of valueForUndefinedKey: is to throw an NSUndefinedKeyException.

Looking back at the crash example, [dict valueForKey: @ "@ theKey"]; Removes @ from the key and changes it to [dict valueForKey: @ "theKey"];, dict does not have a property like theKey. Instead, it executes [dict valueForUndefinedKey: @ "theKey"]; and then crash out when an NSUndefinedKeyException is thrown.

ObjectForKey: And valueForKey: In most cases, the same result is returned. However, if the key starts with @, valueForKey: becomes a big pitfall. We recommend that you only use objectForKey: In NSDictionary to set the value.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.