// 1. Key-value observation
// 2. It provides a mechanism. When the attribute of the specified object is modified, the object will receive a notification.
// 3. Only objects that comply with the KVC (key-valuedcoding) mechanism can use KVO.
// 4. Implementation Process
// ① Register and specify the observer
// ② Implement the callback Method
// ③ Remove observation
- (
void
)viewDidLoad
{
[
super
viewDidLoad
];
// Do any additional setup after loading the view from its nib.
// Instantiate an observer object
self
.stockForKVO
= [[
StockData
alloc
]
init
];
// Initialization
[
self
.stockForKVO
setValue
:
@"searph"
forKey
:
@"stockName"
];
// KVC
[
self
.stockForKVO
setValue
:
@"10.0"
forKey
:
@"price"
];
// KVC
// Listen and display it in lable-register the observer
[
self
.stockForKVO
addObserver
:
self
forKeyPath
:
@"price"
options
:
NSKeyValueObservingOptionNew
context
:nil
];
self
.myLable
.textColor
= [
UIColor
redColor
];
self
.myLable
.text
= [
self
.stockForKVO
valueForKey
:
@"price"
];
// Create button
UIButton
*button = [
UIButton
buttonWithType
:UIButtonTypeRoundedRect];
[button
setFrame
:CGRectMake(
9
0
,
1
5
0
,
1
4
0
,
4
2
)];
[button
setTitle
:
@ "Button"
forState
:UIControlStateNormal];
[button
addTarget
:
self
action
:
@selector
(buttonAction)
forControlEvents
:UIControlEventTouchUpInside];
[
self
.view
addSubview
:button];
}
// Button RESPONSE METHOD
- (
void
)buttonAction
{
[
self
.stockForKVO
setValue
:
@"20.0"
forKey
:
@"price"
];
}
// Callback Method
- (
void
)observeValueForKeyPath:(
NSString
*)keyPath
ofObject
:(
id
)object
change
:(
NSDictionary
*)change
context
:(
void
*)context
{
if
([keyPath
isEqualToString
:
@"price"
])
{
self
.myLable
.text
= [
self
.stockForKVO
valueForKey
:
@"price"
];
}
}
- (
void
)dealloc
{
// Remove the observer
[
self
.stockForKVO
removeObserver
:
self
forKeyPath
:
@"price"
];
}