-1

I can't figure out how to simple observe change in one object property, that's not working as expected.

Here my code:

- (void)observeBasketValueChane:(MyObject*)theObject{
    [theObject addObserver: self
                  forKeyPath: @"value"
                     options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
                     context: NULL];

// not working
    theObject.value = 5;

// will work
    [theObject willChangeValueForKey:@"value"];
    [theObject setValue: [NSNumber numberWithInt: 3] forKey:@"value"];
    [theObject didChangeValueForKey:@"value"];
}

The Apple doc said KVO on dot syntax is automatically done. My value property is synthesized on MyObject but that is not working as expected. Note that Myobject is a coreData object. But i don't see why it will change something since i have synthesized the method. Thank you for your help.

* edit

As Quellish said, my property was defined as

@property (nonatomic) int32_t value;

And that will not works.

The correct way is

@property (nonatomic) NSNumber* value;
Mr Bonjour
  • 3,330
  • 2
  • 23
  • 46
  • 1
    Can you update your question with information on how the property "value" is defined, and wether you have implemented your own accessors? You should NOT have to call will/didChangeValueForKey when using properties, only when accessing an ivar directly (which you shouldn't do). – quellish Apr 15 '14 at 07:46

1 Answers1

3

This line:

theObject.value = 5;

Will not work, because you are setting a property that represents an NSNumber with an integer. Try this instead to see if it fixes your issue:

theObject.value = [NSNumber numberWithInteger:5];

You seem to have some other issues with how you are implementing KVO, but it looks like the above will fix the problem you are describing in this question.

quellish
  • 21,123
  • 4
  • 76
  • 83
  • Also, `@5` or `@([self calculated5])` ... I personally hate the verbosity of NSNumber initializers now that the `@` can object-ify so many things, including primitive numbers. – greymouser Apr 15 '14 at 13:48