@interface Student : NSObject
{
NSString *name;
NSString *courseName;
}
@end
Student.m文件
@implementation Student
-(void)changeCourseName:(NSString*) newCourseName
{
courseName = newCourseName;
}
@end
@property(nonatomic,strong) Student *stu;
@end
@implementation WBViewController
@synthesize stu = _stu;
{
if ([keyPath isEqual:@"courseName"])
{
NSLog(@"PageView课程被改变了 %s",(char*)context); //输出被观察者携带的参数
NSLog ( @"PageView 新课程是 :%@ 老课程是 :%@" , [change objectForKey: @"new" ],[change objectForKey: @"old" ]);
}
{
[super observeValueForKeyPath:keyPath
ofObject:object
change:change
context:context];
}
}
-( void ) viewWillAppear:( BOOL )animated
{
char *param = "I am a student!" ;
self . stu = [[ Student alloc ] init ];
[self.stu addObserver:self
forKeyPath:@"courseName"
options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew
context:param]; //携带参数
[self.stu changeCourseName:@"数学课"];
NSLog(@"初始值:%@", [self.stu valueForKey:@"courseName"]);
}
-(void) viewDidAppear:(BOOL)animated
{
// [ self . stu setValue : @" 化学课 " forKey: @"courseName" ];
{
[self.stu removeObserver:self forKeyPath:@"courseName" context:nil];
2013-10-24 21:44:51.828 KVODemo[7135:c07] PageView课程被改变了 I am from a student!
{
if ([key isEqualToString:@"courseName"]) {
return NO;
}
return [super automaticallyNotifiesObserversForKey:key];
}
{
/**************3.利用KVC机制改变被观察者属性值****************/
//[self.stu setValue:@"化学课" forKey:@"courseName"];
[self.stu willChangeValueForKey:@"courseName"];
[self.stu setCourseName:@"化学课"];
[self.stu didChangeValueForKey:@"courseName"];
}
Key-Value Observing Implementation Details
Automatic key-value observing is implemented using a technique called isa-swizzling.
The isa
pointer, as the name suggests, points to the object's class which maintains a dispatch table. This dispatch table essentially contains pointers to the methods the class implements, among other data.
When an observer is registered for an attribute of an object the isa pointer of the observed object is modified, pointing to an intermediate class rather than at the true class. As a result the value of the isa pointer does not necessarily reflect the actual class of the instance.
isa
pointer to determine class membership. Instead, you should use the
class
method to determine the class of an object instance.