Kvc Method and Realization principle

Source: Internet
Author: User

KVC provides a way to dynamically access object properties and member variables at runtime, not compile time, and the method does not need to call get and set methods and variable instances to access the object, KVC the default implementation method is Nsoject provided, and this method and support object also supports simple data types.
First, there are several ways to access variables in OC:
1, set to public type, through direct access:
The code is:
@interface Book:nsobject
{
@public
NSString *name;
}
Book *book=[[bookalloc]init];
Book->[email protected] "Hello";
NSLog (@ "Val is%@", book->name);
2. Using attribute Access
3. Use KVC, even if the property is private and can be accessed
@interface Book:nsobject
{
@private
NSString *name;
}
Book *book=[[book Alloc]init];
[Book setvalue:@ "Hello" forkey:@ "name"];
NSLog (@ "Val is%@", [bookvalueforkey:@ "name"]);
Second, KVC path access
In addition to setting the value by key, the key/value encoding also supports the specified path, which, like the file system, is separated by the "dot" number
[Book valueforkeypath:@ "Authorobj.name"]
Sample
Book *book=[[book alloc] init];
[Book setvalue:@ "Hello" forkey:@ "name"];
NSLog (@ "Val is%@", [Book valueforkey:@ "Name"]);

Author *authorobj=[[author alloc] init];
[Authorobj setvalue:@ "Niudun" forkey:@ "name"];
[Book Setvalue:authorobj forkey:@ "Authorobj"];

NSLog (@ "the author of Book is%@", [Book valueforkeypath:@ "Authorobj.name"]);
Third to first to many
@interface Book:nsobject
{
@private
NSString *name;
Author *authorobj;
Nsarray *relativebooks;

}//KVC
Book *book=[[book alloc] init];
[Book setvalue:@ "Hello" forkey:@ "name"];
NSLog (@ "Val is%@", [Book valueforkey:@ "Name"]);

KeyPath
Author *authorobj=[[author alloc] init];
[Authorobj setvalue:@ "Niudun" forkey:@ "name"];
[Book Setvalue:authorobj forkey:@ "Authorobj"];
NSLog (@ "the author of Book is%@", [Book valueforkeypath:@ "Authorobj.name"]);

One-to-many
Nsmutablearray *array=[nsmutablearray Arraywithcapacity:3];
for (int i=0; i<3; i++) {
Book *bookobj=[[book alloc] init];
NSString *name=[nsstring stringwithformat:@ "job_%d", I];
[Bookobj setvalue:name forkey:@ "name"];
[Array addobject:bookobj];
[Bookobj release];
}
[Book Setvalue:array forkey:@ "Relativebooks"];
Nsarray *arr=[book valueforkeypath:@ "Relativebooks.name"];
NSLog (@ "arr is%@", arr);


Iv. KVC supports simple budgeting such as Max, Min, Sum, where the field of the operation must be the base data type or the NSNumber type




V. KVC support for numerical and structural types
A set of mechanisms that do not support data of numerical and structural size will greatly discount its usefulness. Fortunately, Apple has done a good job of supporting this in KVC. KVC can automatically package or unpack data of numerical or structural size into NSNumber or Nsvalue objects for adaptation purposes.
For example, the person class has a num attribute of all Nsinteger types
① Modifying values
We use the KVC technique to set the value of the Age property in the following ways:
[_person setvalue:[nsnumber numberwithinteger:5] forkey:@ "num"];
We assign num a NSNumber object, KVC automatically converts the NSNumber object to a Nsinteger object, and then calls the appropriate accessor method to set the value of age.
② Get Value
Similarly, get the Age property value in the following way:
[Person valueforkey:@ "num"];
At this point, the value of NUM is returned in the form of NSNumber.
The method definition of the realization principle of the VI and KVC
In iOS, the mechanism of class properties can be accessed directly using the string's name (key) through KVC. Instead of being accessed by invoking a setter, getter method.
KVC is the technical basis of KVO, Core Data and cocoabindings, and they all take advantage of the dynamics of OC.
Nskeyvaluecodingprotocol
The Setvalue:forkey is how to access the property value
The KVC method implements get, set method and instance variable access, KVC SetValue method and GetValue method use the following techniques in order:
1. Check if there is set<key>: Method
If the member is using @property, @synthsize processing because @synthsize tells the compiler to automatically generate SET&LT;KEY&GT;: The set method of the format, so this case will be searched directly.
2. Check the name-_<key>,-_is<key> (valid only for Boolean values),-_set<key>: method;
Then search for the member names in _<key>,_is<key>,<key>,is<key> order.
3. Direct access to instance variables. The instance variable can be named:<key> or _<key>;
4. Calling Method Setvalue:forundefinedkey
Eighth, Valueforkey is how to access the value of the property
Similar to the SetValue execution order above, the set method is changed to the Get method, and the method Valueforundefinedkey is called when all is invalidated.
Ninth, Method rewrite
If our class does not have either a key or _key corresponding Set/get method, or a key or _key corresponding instance variable, but to use the SetValue and GetValue methods, you must override the function SetValue: Forundefinedkey and Valueforundefinedkey.
Here we can take advantage of OC's Association mechanism
1. What is the correlation mechanism
OC provides two sharing mechanisms, one category, one associative,category only extension methods, and associative to extend the properties.
The correlation mechanism is based on keywords, and we can add any number of associations to any object, each using a different keyword. An association is a guarantee that the associated object is available throughout the life cycle of the associated object (and does not cause the resource to be non-recyclable in a garbage-collected environment). The <objc/runtime.h> header file must be introduced using the correlation mechanism
2.objc_setassociatedobject Creating an Association
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. The function requires four parameters: the source object, the keyword, the associated object, and an associated policy
Parameter description:
Object: Represents the Source object
Key: Key Words
Value: Represents the associated object
Policy: Association policy, which indicates whether related objects are associated by assignment, preserving a reference or copying it, and whether the association is atomic or non-atomic. The correlation policy here is similar to the Declaration property.
Policy has a value of four:
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, 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 getting associated objects
Objc_export ID objc_getassociatedobject (ID object, const void *key)
__osx_available_starting (__mac_10_6, __iphone_3_1);
4.objc_removeassociatedobjects removes all associations for this object, which is generally not recommended because he disconnects all associations. This function is only used 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);
Nsarray *arr=[nsarray arraywithobjects:@ "One", nil];
Objc_setassociatedobject (arr, @ "Hello", @ "World", Objc_association_retain);

NSString *ret= (NSString *) Objc_getassociatedobject (arr, @ "Hello");
NSLog (@ "The result is%@", ret);




5. Objc_setassociatedobject with nil to disconnect the specified key
6. Implementation of the Override method
-(void) SetValue: (ID) value Forundefinedkey: (NSString *) Key {
if (value = = nil) {
value = [NSNull null];
}
Objc_setassociatedobject (self, (__bridge const void *) (key), value, Objc_association_retain);
}


-(ID) Valueforundefinedkey: (NSString *) Key {
ID target = Objc_getassociatedobject (self, (__bridge const void *) (key));
if ([Target Iskindofclass:[nsnull class]])
return nil;
return target;
}











Kvc Method and Realization 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.