I have a view controller with a button that I'd like to enable if myArray.count > 0
. I got KVO working initially, but it doesn't update.
My button property declared here:
@property (strong, nonatomic) IBOutlet UIBarButtonItem *saveButton;
I'd like to enable/disable the button based on the count of items in an array:
@property (nonatomic, strong) NSMutableArray *myArray;
Items are added/removed to the array via didSelectRowAtIndexPath
I found a couple of posts on the topic of observing an NSMutableArray, every post I've seen seems enormous amount of code to implement something so simple.
I added this to viewDidLoad
after myArray
is instantiated:
// Add KVO for array
[self.saveButton addObserver:self forKeyPath:@"myArray" options:(NSKeyValueObservingOptionInitial) context:nil];
I added this method to do something when there's a change to myArray
:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"myArray"]) {
if (self.myArray.count > 0) {
NSLog(@"KVO: myArray.count > 0");
[self.saveButton setEnabled:YES];
} else {
NSLog(@"KVO: myArray.count is ZERO");
[self.saveButton setEnabled:NO];
}
}
}
I know I'm missing something simple, but what is proving elusive.