Torben
Torben

Reputation: 101

KVO (IOS 5) on simple types (non NSObject)

I'm having problems to make the IOS (objective-c) KVO work for a key of type int.

My class declares a property sampleValue of type int. As int doesn't automatically implement the KVO functionality I've overrided the method automaticallyNotifiesObserversforKey as this:

+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)theKey {

    BOOL automatic = NO;
    if ([theKey isEqualToString:@"sampleValue"]) {
        automatic = NO;
    } else {
        automatic=[super automaticallyNotifiesObserversForKey:theKey];
    }
    return automatic;
}

The method is called just as I would expect is to be. I also have implemented a setter method for the sampleValue property like this:

- (void) setSampleValue:(int)newSampleValue
{
    [self willChangeValueForKey:@"sampleValue"];
    sampleValue = newSampleValue;
    [self didChangeValueForKey:@"sampleValue"];
}

Setting up the observer in the observer class is done like this (dc is the instance of the observed object):

[dc addObserver:self forKeyPath:@"sampleValue" options:NSKeyValueObservingOptionNew context:NULL];

However, when the sampleValue is updated, no notification is sent to my observer object. Updating another property of type NSDate works absolutely fine.

Can anyone help me figure out what I'm doing wrong or what I should do to make this work.

Best regards Tomo

Upvotes: 3

Views: 2793

Answers (1)

Caleb
Caleb

Reputation: 124997

Maybe I'm missing something in your question, but you can observe properties of type int just as easily as other types without doing anything special.

Try removing your +automaticallyNotifiesObserversForKey: override and your -setSampleValue: setter, and just synthesize the accessors for sampleValue:

@synthesize sampleValue;

int is the type of the value that corresponds to key @"sampleValue", but it's not the thing being observed. The object being observed is dc, and it'll take care of sending the proper notification when the sampleValue property is changed.

Upvotes: 7

Related Questions