Adrian
Adrian

Reputation: 16715

Enable/disable a button based on count in NSMutableArray

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.

Upvotes: 0

Views: 1508

Answers (2)

ChenYilong
ChenYilong

Reputation: 8673

The catch is that NSMutableArray don't respect KVO, so observing the key path count won't work.This WILL work if you access the array correctly:

something = [self mutableArrayValueForKey:@"a"]; 
[something addObject:foo];

you may get answer at here : KVO With NSMutableArray

Observing count in NSMutableArray

For chinese 🇨🇳 [Observing count in NSMutableArray] you may get answer at :

change

// Add KVO for array
[self.saveButton addObserver:self forKeyPath:@"myArray" options:(NSKeyValueObservingOptionInitial) context:nil];

to

// Add KVO for array
[self addObserver:self forKeyPath:@"myArray" options:(NSKeyValueObservingOptionInitial) context:nil];

Upvotes: 0

AppyMike
AppyMike

Reputation: 2064

If the only time the array can be edited is through didSelectRowAtIndexPath then why not just enable/disable the button there.

 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  {
    //current code    

    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];
    }
}

Upvotes: 1

Related Questions