KVC/KVO and notification sample code

| No Comments | No TrackBacks

#pragma mark KVO

- (void)observeValueForKeyPath:(NSString *)keyPath

                      ofObject:(id)object

                        change:(NSDictionary *)change

                       context:(void *)context

{

NSLog(@"dict= %@ obj= %@,keypath=%@",change,object,keyPath);

//    if (object ==xxx) {

//        if ([keyPath isEqualToString:@"title"]) {

//            

//        }else if ([keyPath isEqualToString:@"name"]) {

//            

//        }

//    } else if(object == bbb){

//        

//    }

    if (context == 123) {

        

    } else if(context == 456){

        

    }

    

}

-(void)traceObj:(Entry*)obj

{

[obj addObserver:self

  forKeyPath:@"title"

options:0

context:123];

    [obj addObserver:self

  forKeyPath:@"name"

options:0

context:456];

    [objB addObserver:self

  forKeyPath:@"name"

options:0

context:NULL];

}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

-(void)viewDidLoad

{

[super viewDidLoad];


Entry *entry =[[Entry alloc] init];

[self traceObj:entry];

[entry setValue:@"abc" forKey:@"title"];

id msg=[entry valueForKey:@"titl"];

NSLog(@"%@",msg);

[[NSNotificationCenter defaultCenter] addObserver:self 

selector:@selector(keyboardShow:)

name:UIKeyboardWillShowNotification 

  object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self 

selector:@selector(keyboardShow:)

name:UIKeyboardWillHideNotification

  object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self 

selector:@selector(textChanged:)

name:UITextFieldTextDidChangeNotification

  object:nil];

}

-(void)textChanged:(NSNotification*)noti

{

NSLog(@"%@ %@",input.text,[noti userInfo]);

NSString *sTr =input.text;

if ([sTr length] >=10) {

input.text = [sTr substringWithRange:NSMakeRange(0,9)];

UIAlertView *alert=[[[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:@"2",@"cancel",nil] autorelease];

[alert show];

}

NSMutableArray *array=[[NSMutableArray alloc] initWithCapacity:10];

}

-(void)keyboardShow:(NSNotification*)noti

{

if ([[noti name] isEqualToString:UIKeyboardWillShowNotification]) {

input.center = CGPointMake(input.center.x, input.center.y-200);

} else {

input.center = CGPointMake(input.center.x, input.center.y+200);

}


}

######################################

@implementation Entry

@synthesize title;

@synthesize price;

@synthesize image53;

@synthesize image;



-(id)valueForUndefinedKey:(NSString *)key

{

return [NSString stringWithFormat:@"%@ not have value for key %@",self,key];

}

-(void)setValue:(id)value forUndefinedKey:(NSString *)key

{

}


Enhanced by Zemanta

No TrackBacks

TrackBack URL: http://iphone.ipsw.info/mt/mt-tb.cgi/372

Leave a comment