Jay Q.
Jay Q.

Reputation: 4999

KVO not working with UISwitch

For the life of me I can't get KVO working with UISwitch. I have a custom UITableViewCell with a UISwitch added through Interface Builder. I created an IBOutlet for the UISwitch and linked it to theSwitch variable.

- (id)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
           [theSwitch addObserver:self forKeyPath:@"on" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSLog(@"toggled switch");
}

observeValueForKeyPath:ofObject:change:context is never called!

Upvotes: 6

Views: 2443

Answers (2)

RTasche
RTasche

Reputation: 2644

theSwitch might not have been initialized when you add the observer. try adding the observer in awakeFromNib.

Upvotes: 0

jtbandes
jtbandes

Reputation: 118681

I'm not sure, but it's possible that UISwitch simply isn't KVO-compliant.

No matter, because you can just use control events:

[theSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
// ...
- (void)switchChanged:(UISwitch *)sender {
    if (sender.on) {
        // ...
    }
}

Upvotes: 12

Related Questions