Key-value observations provide a mechanism that allows the viewer object to be notified when a particular property of another object is modified. This mechanism is particularly useful for communication between the model of the application and the controller. Typically, the controller object observes the properties of the model object, while the View object observes the properties of the model object through the controller. In addition, a model object can observe other model objects.
To receive a key-value observation notification for a property, you need to:
The observed object invokes the AddObserver:forKeyPath:options:context: Method registers the Observer object;
The observation class must implement the ObserveValueForKeyPath:ofObject:change:context: method.
Example
1. Create a single View application and enable arc;
2. Create a new StockData class, the header file looks like this:
@interface Stockdata:nsobject
@property (Assign, nonatomic) cgfloat price;
@end
Implementation code can not be processed first;
3. In viewcontroller.m, first modify the interface definition, the code is as follows:
#import "StockData.h"
@interface Viewcontroller ()
{
stockdata *_stock;
Uilabel *_label;
}
@end
4. Modify the Viewdidload method as follows:
-(void) viewdidload
{
[super viewdidload];
Do no additional setup after loading the view, typically from a
nib.
1. Initialize stockdata
_stock = [[StockData alloc]init];
2. The new Label control displays the price property of the StockData
_label = [[Uilabel alloc]initwithframe:cgrectmake (0, MB, $
)];
[_label Settextalignment:nstextalignmentcenter];
[Self.view Addsubview:_label];
3. Add observer watch Price property
[_stock addobserver:self
forkeypath:@ ' price '
options:nskeyvalueobservingoptionnew
Context:nil];
4. Test property Changes
[_stock setprice:20];
[_stock setprice:30];
[_stock setprice:40];
}
5. Implement ObserveValueForKeyPath:ofObject:change:context: Method, under the Viewdidload method, add the following code:
-(void) Observevalueforkeypath: (NSString *) KeyPath
ofobject: (ID) object Change
: (nsdictionary *)
change Context: (void *) context
{
if ([KeyPath isequal:@ ' price ']) {
NSLog (@ "New Price is%@", change[@ "new"));
[_label settext:[nsstring stringwithformat:@ "%0.02f",
_stock.price]];
}
6. Generate and run the program, the label should show 40.00, but in the console can see 3 times the price property changes.
Add
For this example, the code for the Observer is not deleted because it supports arc. However, for more complex applications, it is necessary to remove the observer listener when it is not needed. To do this, you can invoke the following code:
[_stock removeobserver:self forkeypath:@ "Price"];
Finish the work!
See more highlights of this column: http://www.bianceng.cn/Programming/project/