KVC implementation principle

Source: Internet
Author: User

KVC implementation principle

In iOS, KVC can directly use the string name (key) to define class attributes. Instead of using the setter and getter methods.

KVC is the technical basis of KVO, core data, and cocoabindings. They all use the dynamic nature of OC.

About the use of KVC, blog http://blog.csdn.net/richard_rufeng/article/details/15409123 has a detailed introduction, here we focus on the implementation of KVC principle.

1. method definition

Nskeyvaluecodingprotocol

2. setvalue: How does forkey access the attribute value?

The KVC method implements get, set, and instance variable access. The KVC setvalue method and getvalue method use the following techniques in sequence:

1. Check whether the set <key>: method exists

If the @ property, @ synthsize is used for processing, because @ synthsize tells the compiler to automatically generate the set <key>: Set Method in the format, this will be searched directly.

2. Check whether the name is-_ <key>,-_ is <key> (valid only for boolean values), and-_ set <key>: method;

Search for member names in the order of _ <key>, _ is <key>, <key>, and is <key>.

3. Access instance variables directly. The instance variable can be <key> or _ <key>;

4. Call method setvalue: forundefinedkey

Third, how does valueforkey access attribute values?

Similar to the execution sequence of setvalue, the set method is changed to the get method. When all the values are invalid, the valueforundefinedkey method is called.

4. Method Rewriting

If our class neither has the set/get method corresponding to the key or _ key nor the instance variable corresponding to the key or _ key, but we need to use the setvalue and getvalue methods, you must override the setvalue: forundefinedkey and valueforundefinedkey functions.

Here we can use the OC association mechanism

1. What is association mechanism?

OC provides two sharing mechanisms: category, associative, and category. associative can only extend attributes.

The association mechanism is based on keywords. We can add any number of associations to any object, and each object can use different keywords. Association ensures that the associated object is available throughout the lifecycle of the associated object (in the garbage collection environment, the resource cannot be recycled ). The header file <objc/runtime. h> must be introduced to use the association mechanism.

2. objc_setassociatedobject

Objc_export void objc_setassociatedobject (ID object, const void * Key, id value, objc_associationpolicy Policy)

_ Osx_available_starting (_ mac_10_6, _ iphone_3_1 );

Objc_setassociatedobject to associate an object with another object. This function requires four parameters: source object, keyword, associated object, and an association policy.

Parameter description:

Object: indicates the source object.

Key: keywords

Value: indicates the associated object.

Policy: An association policy. The association policy indicates whether the related objects are associated by assigning values, retaining references, or copying objects. Whether the association is atomic or non-atomic is also true. The association policy here is similar to the attribute declaration.

The policy has four values:

OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object.                                             *   The association is not made atomically. */    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied.                                             *   The association is not made atomically. */    OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object.                                            *   The association is made atomically. */    OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied.                                            *   The association is made atomically. */


3. objc_getassociatedobject

Objc_export ID objc_getassociatedobject (ID object, const void * key)

_ Osx_available_starting (_ mac_10_6, _ iphone_3_1 );

4. objc_removeassociatedobjects deletes all the associations of the object. Generally, this function is not recommended because it disconnects all associations. This function is used only when the object needs to be restored to the original state.

Objc_export void objc_removeassociatedobjects (ID object)

_ Osx_available_starting (_ mac_10_6, _ iphone_3_1 );

5. objc_setassociatedobject with nil to disconnect a specified key

6. Implementation of rewrite Methods

<span style="font-size:18px;">- (void)setValue:(id)value forUndefinedKey:(NSString *)key {    objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_RETAIN);}- (id)valueForUndefinedKey:(NSString *)key {    id target = objc_getAssociatedObject(self, key;    if ([target isKindOfClass:[NSNull class]])        return nil;    return target;}</span>





KVC implementation principle

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.