0

I have:

- (void) observeValueForKeyPath:(NSString *)keyPath
                       ofObject:(Player *)object
                         change:(NSDictionary<NSString *,id> *)change
                        context:(void *)context
{
    switch (object.Status)
    {
        case 0:
            NSLog(@"%ld Play" ,object.Status);
            break;
        case 1:
            NSLog(@"%ld Pause", object.Status);
            break;
        case 2:
            NSLog(@"%ld Stop", object.Status);
            break;
        case 3:
            NSLog(@"%ld RewindF", object.Status);
            break;
        case 4:
            NSLog(@"%ld RewindB", object.Status);
            break;
        default:
            break;
    }
}

And:

[player addObserver:classA
         forKeyPath:@"Status"
            options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
            context:nil];

I want to see on screen 2 values: NewValueKey and OldValueKey but I don't how to NSLog OldValue too. I tried sth that

NSString *oldValue = [change objectForKey:NSKeyValueObservingOptionNew]; 

But I got error

"NSUInteger too String"

How to connect old and new in one NSLog :)?

Borys Verebskyi
  • 4,160
  • 6
  • 28
  • 42
Laxsion12
  • 67
  • 1
  • 8

1 Answers1

0

Well if you specifically want to just log out your old and new status-- you need to type cast them (Because you receive them as NSNumber)

Like this:

  NSLog(@"OLD VALUE: %@ \nNEW VALUE: %@", [[change objectForKey:NSKeyValueChangeOldKey] stringValue], [[change objectForKey:NSKeyValueChangeNewKey] stringValue]);

Also note that you want to use the Key constant, e.g NSKeyValueChangeNewKey. Not the option constant, e.g NSKeyValueObservingOptionNew

EDIT: @Joost has corrected me, -objectForKey returns an NSNumber. So to get a string to log, you need to send that object the -stringValue message

A O
  • 5,516
  • 3
  • 33
  • 68
  • You should also be checking the keyPath to ensure that the `change` dictionary contains what you think it does. If, for example you have this object observing a separate object-- and the KVO notification gets sent, then the `NSLog` here could throw an exception if the values in the change dictionary cannot be casted into a `long` – A O Dec 21 '15 at 22:18
  • Your **note** is actually the problem here, not the casting. Actually, the casting you propose is incorrect as `objectForKey:` returns an object, so casting to `long` is incorrect. – Joost Dec 21 '15 at 22:55
  • Ah sorry, you're right. Brain fart. Read his "error" and it threw me off – A O Dec 22 '15 at 16:14