Bindings working from IB, not from my addObserver...

77 Views Asked by At

My Document-based app was created without storyboards in Xcode 6.3 so it began life without a window controller (I still don't have a window controller -- just trying to give some background and context).

I have a class structure implemented for working with a gradient and storing it's formative values in my document.

My Document class holds a reference to a Theme object.

My Theme class holds a reference to a Gradient object.

My Gradient class holds a reference to an NSNumber for the start point of the gradient.

In IB an NSSlider is bound to File's Owner, with Model Key Path of "self.theme.gradient.startPointX" This works fine, as evidenced by Gradient.m -didChangeValueForKey logging out the specific key whose value is being changed.

So why doesn't a similar notification occur in my Document class when the slider for the gradient start point is changed after I have asked to observe it?

Document.m

- (instanceType)init {
    self = [super init];
    if (self) {
        self.theme = [[MyTheme alloc] init];
        // first attempt -- not live when second attempt is compiling
        [self addObserver:self
               forKeyPath:@"theme.gradient.startPointX"
                  options:NSKeyValueObservingOptionNew
                  context:@"myDocument"];
        // second attempt -- not live when the first attempt is compiling
        [self.theme.gradient addObserver:self
                              forKeyPath:@"startPointX"
                                 options:NSKeyValueObservingOptionNew
                                 context:@"myDocument"];
    }
    return self;
}

- (void)didChangeValueForKey:(NSString *)key
{
    NSLog(@"Document notified that \"%@\" has changed.", key);
}

-

Theme.m

- (instancetype)init
{
    if (self = [super init]) {
        self.gradient = [[Gradient alloc] init];
    }
    return self;
}

-

Gradient.h

@interface Gradient : NSObject

@property (strong, nonatomic) NSNumber *startPointX;

@end 

-

Gradient.m

- (instancetype)init
{
    if (self = [super init]) {
        self.startPointX = @(0.47f);
    }
    return self;
}

- (void)didChangeValueForKey:(NSString *)key
{
    if ([key isEqualToString:@"startPointX"]) {
        NSLog(@"Gradient notified a change to %@ has occurred.", key);
}
1

There are 1 best solutions below

0
On BEST ANSWER

It turns out that if you implement -didChangeValueForKey: it blocks/suspends normal notification of those properties you might be observing.

Commenting out my Gradient.m implementation of

- (void)didChangeValueForKey:(NSString *)key
{
    NSLog(@"'%@' has been changed.", key);
}

caused my observations from Document to begin working fine.