An example is given to explain the KVO and KVC mechanism in objective-c _java

Source: Internet
Author: User

An analysis of KVO examples

Recently encountered a problem, in the process of a comment interface in the project, because the direct use of the UIWebView to display a list of comments, the results of the page up and down there is a cgsize (320,65) of the messy ads, Very unsightly. The head advertisement because very convenient in the head coordinates pastes on own logo solves, but the tail, because each page's comment length is different, the coordinate is different, thus cannot give the dead coordinates to affix the logo, after thinking, through Kvo very good solves this question.
@KVO Overview:
KVO, which is: Key-value observing, provides a mechanism for the object to receive notification when the properties of the specified object have been modified.
Simply put, the KVO automatically notifies the corresponding observer when the properties of the observed object are modified each time it is specified.

Use the following steps:
1. Register, specify the attributes of the observed person,
2. Implementation callback method
3. Trigger callback method
4. Removal observation

Code instance:

Copy Code code as follows:

-(void) viewdidload{

KVO, as an observer, as long as the attribute "Contentsize" is changed, the callback method will notify the
[_webview.scrollview addobserver:self forkeypath:@ "contentsize" Options:nskeyvalueobservingoptionnew Context:NULL] ;
}

callback method
-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: ( Voidvoid *) Context
{
if (object = = _webview.scrollview && [keypath isequaltostring:@ "Contentsize"])
{
Get the maximum y-coordinate
Cgsize size = _webview.scrollview.contentsize;

if (Size.Height > 568.0) {

Blocking ads
_hidebottomimage = [[Uiimageview alloc] Initwithframe:cgrectmake (0, size.height-67, ScreenWidth, 67)];
_hidebottomimage.image = [uiimage imagenamed:@ "banner"];
[_webview.scrollview Addsubview:_hidebottomimage];
[_hidebottomimage release];
}
}
Else
{
Methods to invoke the parent class
[Super Observevalueforkeypath:keypath Ofobject:object Change:change Context:context];
}
}

-(void) dealloc{//----> can also invoke Dealloc methods in an ARC environment, except that you do not need to write [super Dealloc]

Remove KVO, or cause resource leaks
[_webview.scrollview removeobserver:self forkeypath:@ "Contentsize"];
[Super Dealloc];

}

The above is for the Contentsize property, the other properties, and so forth

Kvc
Typically, we assign values and values through the set and get methods of attributes, and here we introduce key-value-coding (KVC) key-value encodings to assign and value the properties of a class.
1. Basic mode (SetValue:forKey:valueForKey)

Copy Code code as follows:

---Define a student class (. m file without any action)
#import <Foundation/Foundation.h>


@class Hmtclass;
@interface hmtstudent:nsobject{

NSString * _NAME;

BOOL _test;
BOOL _istest;
BOOL test;
BOOL istest;

}

@property (nonatomic,copy) nsstring * name;
@property (nonatomic,copy) nsstring * sex;
@property (nonatomic,assign) Nsinteger age;
@property (Nonatomic,strong) hmtclass * HMTCLASS;

@end

---main file
Hmtstudent * student = [[Hmtstudent alloc] init];

Student.hmtclass = [[Hmtclass alloc] init];
Student.name = @ "Humingtao"; The Set method assigns a value

KVC Assign Value
[Student setvalue:@ "Mawei is Dog" forkey:@ "name"];
[Student setvalue:@ "M" forkey:@ "sex"];
[Student setvalue:@ (Ten) forkey:@ "age"];
Take value
NSLog (@ "%s__%d__|%@", __function__,__line__,[student valueforkey:@ "name"));

Special attention:
I also defined 4 bool value variables in the class to validate the KVC Access property key order
[Student setvalue:@ (YES) forkey:@ "test"];

The result: _test->_istest->test->istest

2. Key path access (for properties of a property in a class SetValue:ForKeyPath:forKeyPath)

Copy Code code as follows:

Create a Class class
@interface Hmtclass:nsobject

@property (nonatomic,copy) nsstring * name;

@end

Then a class attribute is written in the student class in the 1th in front Hmtclass
Copy Code code as follows:

Hmtclass *hmtclass = [[Hmtclass alloc]init];
[Hmtclass setvalue:@ "Universe class" forkey:@ "name"];
[Student Setvalue:hmtclass forkey:@ "Hmtclass"];
NSString *hmtclassname = [Student valueforkeypath:@ "Hmtclass.name"];

You can also save a value like this
[Student setvalue:@ "Cosmic Class" forkeypath:@ "Hmtclass.name"];
Student.hmtClass.name = [Student valueforkeypath:@ "Hmtclass.name"];

3. Automatic encapsulation of basic data types
We add fractional attributes to the student class Nsinteger number;
Copy Code code as follows:

#import <Foundation/Foundation.h>
@class Hmtclass;
@interface Hmtstudent:nsobject
{
NSString *_name;

Nsinteger number;
}
@end

[Student setvalue:@ "forkeypath:@" "number"];
NSString *number = [Student valueforkey:@ "number"];

You can see the property value set with the nsstring* type @ "100", and our properties are Nsinteger types, and access is OK.

4. Operation Set
Add an array nsarray to the student class to represent the other students.

Copy Code code as follows:

#import <Foundation/Foundation.h>
@class Hmtclass;
@interface Hmtstudent:nsobject
{
Nsarray *manystudents;
}
@end

Student *student1 = [[Hmtstudent alloc]init];
Student *student2 = [[Hmtstudent alloc]init];
Student *student3 = [[Hmtstudent alloc]init];
[Student1 setvalue:@ "" forkey:@ "number"];
[Student2 setvalue:@ "" forkey:@ "number"];
[Student3 setvalue:@ "forkey:@"];
Nsarray *array = [Nsarray arraywithobjects:student1,student2,student3,nil];
[Student Setvalue:array forkey:@ "manystudents"];
NSLog (@ "%@", [Student valueforkeypath:@ "Manystudents.number"]);

Print out is an array (200,300,400)

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.