天天看點

KVO/KVC

KVC

Key-Value-Coding

直白了就是鍵值對的意思。先拿到某個對象,知道對象中某個屬性的名稱,可以根據這個名稱來擷取這個對象屬性的值。也可以重新設定這個對象屬性的值。是不是感覺很熟悉

,就好像是    對象.屬性 (person.age)這樣擷取這個資料。還可以設定此屬性的資料。

NSString *originalName = [p valueForKey:@

"name"

];

// using the KVC  accessor (setter) method.

[p setValue:newName forKey:@

"name"

];

NSLog(@

"Changed %@'s name to: %@"

, originalName, newName);

KVO

就是對某個對象,中的某個屬性添加觀察,好像觀察者一樣,隻要發現這對象的屬性值變化了,就告訴某個方法

Key-Value Observing (KVO) 建立在 KVC 之上,它能夠觀察一個對象的 KVC key path 值的變化。舉個例子,用代碼觀察一個 person 對象的 address 變化,以下是實作的三個方法:

  • watchPersonForChangeOfAddress: 實作觀察
  • observeValueForKeyPath:ofObject:change:context: 在被觀察的 key path 的值變化時調用。
  • dealloc 停止觀察

-(

void

) watchPersonForChangeOfAddress:(Person *)p

{

// this begins the observing

[p addObserver:self

forKeyPath:@

"address"

options:0

context:KVO_CONTEXT_ADDRESS_CHANGED];

// keep a record of all the people being observed,

// because we need to stop observing them in dealloc

[m_observedPeople addObject:p];

}

// whenever an observed key path changes, this method will be called

- (

void

)observeValueForKeyPath:(NSString *)keyPath

ofObject:(id)object

change:(NSDictionary *)change

context:(

void

*)context

{

// use the context to make sure this is a change in the address,

// because we may also be observing other things

if

(context == KVO_CONTEXT_ADDRESS_CHANGED) {

NSString *name = [object valueForKey:@

"name"

];

NSString *address = [object valueForKey:@

"address"

];

NSLog(@

"%@ has a new address: %@"

, name, address);

}

}

-(

void

) dealloc;

{

// must stop observing everything before this object is

// deallocated, otherwise it will cause crashes

for

(Person *p in m_observedPeople){

[p removeObserver:self forKeyPath:@

"address"

];

}

[m_observedPeople release];

m_observedPeople = nil;

[super dealloc];

}

-(id) init;

{

if

(self = [super init]){

m_observedPeople = [NSMutableArray

new

];

}

return

self;

}

@end

繼續閱讀