Search code examples
model-view-controlleruiviewkey-value-observingcgrect

KVO on my UIView CGRect property in iOS5 isn't working


I have a ViewController and an UIView and would like to do KVO on an UIView property of type CGRect. For some reason it not working as it should. My code looks like this:

@interface MyView : UIView
@property (nonatomic, assign) CGRect myRect;
@end

@implementation MyView
@synthesize myRect;
...
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
   ...
   //Changing structures values
   myRect.origin.x+=moveVector.x;
   myRect.origin.y+=moveVector.y;
   //assigning new structure
   [self setMyRect:CGRectMake(20, 20, 50, 50)];
   //Both doesn't call
}

I want to observe the CGRect with my viewController. Not sure how strict i should be with MVC here. Btw the CGRect in MyView is just a visible square, which i can move around, so i would say its not a model and should stay in MyView. Please correct em if iam wrong.

Here is my ViewController:

@class MyView;
@interface MyViewController : UIViewController
@property (nonatomic, retain) MyView *overlayView;
@end

@implementation MyViewController
@synthesize overlayView;

- (void)viewDidLoad
{
[super viewDidLoad];
overlayView = [[CameraOverlayView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[overlayView addObserver:self 
              forKeyPath:@"myRect" 
                 options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) 
                 context:NULL];
/*    [self addObserver:self 
       forKeyPath:@"overlayView.myRect"
          options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) 
          context:NULL];*/
self.view = overlayView;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object 
                   change:(NSDictionary *)change context:(void*)context { 
   if( [keyPath isEqualToString:@"myRect"] ) {
      NSLog(@"observeValueForKeyPath");
      CGRect rect = [[change valueForKey:NSKeyValueChangeNewKey] CGRectValue];
   }
}

observeValueForKeyPath is never called, regardless of how i change myRect in MyView. setMyRect: crashes during runtime and i dont really know why. I though synthesize would take care of setters and getters as well as the Keyvalues and changes. Iam also not sure which way of addObserver: is the better way, as i commented out my second attempt to register an Observer.

What iam doing wrong? Isn't it possible to Observe structures? Or only with self written setters and getter? Can it be that UIView is not KVC-Compliant, if so, why does this work? Callback by KVO on a UIView frame property Thanks for any help :-)


Solution

  • My solution is, Iam using a delegate. The Controller is my delegate for view, i think its the way it should be, otherwise UIView would be KVC-Complaint.