lppier
lppier

Reputation: 1987

Value observing in iOS

I have a MorphView.h file in which it tracks the position of the finger on the MorphView object.

#import <UIKit/UIKit.h>

@interface MorphView : UIButton

@property (nonatomic) float morphX;
@property (nonatomic) float morphY;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event ;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

@end

I want to "observe" morphX of button from my Main view controller. I read up on key value observing and did this.

In init of ViewController.m

    MorphView* morphPadBtn = [MorphView buttonWithType:UIButtonTypeCustom];     
    [morphPadBtn addTarget:self action:@selector(morphPressedDown:withEvent:) forControlEvents:UIControlEventTouchDown];
    UIImage *buttonbkImage = [UIImage imageNamed:@"buttonback"];
    [morphPadBtn setBackgroundImage:buttonbkImage forState:UIControlStateNormal];
    [morphPadBtn setAdjustsImageWhenHighlighted:NO];
    morphPadBtn.frame = CGRectMake(300, 200, 300, 300.0);
    [self.view addSubview:morphPadBtn];        
    [morphPadBtn addObserver:morphPadBtn forKeyPath:@"morphX" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

and also did the required function for observing.

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:@"morphX"])
    {
        NSLog(@"Success in observation!"); 
    }
}

However, I don't see "Success in observation" being printed. Am I doing this wrong? All I want is to track my morphX value from my main view controller.

Thanks!

Upvotes: 1

Views: 302

Answers (1)

rmaddy
rmaddy

Reputation: 318884

You added an observer for the key path of morphX, not MorphView.morphX. Change the observer to compare against the correct path.

if([keyPath isEqualToString:@"morphX"])

If you want to ensure this is coming from a specific object then compare the object parameter against some instance variable maintaining a reference to the object.

Also, you are passing the wrong observer to addObserver.... It should be:

[morphPadBtn addObserver:self forKeyPath:@"morphX" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

The observer needs to be the class that implements the observeValueForKeyPath:... method.

Upvotes: 1

Related Questions