0

I have a set of check boxes on my view controller, and they work great. Long story short: A user checks a box, and then taps the save button. Saving after checking a box posts the value 'yes' to a field in my database. However if no box is checked, and my user taps 'save', I'm thrown this error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSDictionary initWithObjects:forKeys:]: count of objects (0) differs from count of keys (1)'

How can I stop the app from crashing if no box is checked, as checking a box is not mandatory? Code below (let me know if you need more - removed convoluted 'save' part of button action).

viewcontroller.m

- (IBAction)myCheck:(id)sender {

    if (!checked17) {

        [myCheck setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
        checked17 = YES;

        self.box = @"Yes";

    }

    else if (checked17) {

        [myCheck setImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
        checked17 = NO;

            self.box = @"No";
    }


}

- (IBAction)submitButton:(id)sender {

    NSDictionary *petOption = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:self.box, nil] forKeys:[NSArray arrayWithObjects:@"value", nil]];
    NSDictionary *checkedFinish = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:petOption] forKey:@"und"];


    [nodeData setObject:checkedFinish forKey:@"field_haveapet"];

}
  • Do you have exception breakpoints enabled? This shows how to do it : http://stackoverflow.com/questions/17802662/exception-breakpoint-in-xcode . Crash your app after enabling this breakpoint and it should show you the exact line on which it crashes. – Losiowaty Sep 15 '16 at 16:04
  • @Losiowaty This is the crash line: NSDictionary *petOption = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:self.checkBox, nil] forKeys:[NSArray arrayWithObjects:@"value", nil]]; – Blair Warner Sep 15 '16 at 16:12

1 Answers1

1

The dictionaryWithObjects counts array size until first nil appears.

So when self.box is nil the first argument is treated as empty array here:

[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:self.box, nil] forKeys:[NSArray arrayWithObjects:@"value", nil]

you need to handle this situation differently, explicitly creating empty NSDictionary when self.box is nil, for example.

Anton Malyshev
  • 8,686
  • 2
  • 27
  • 45
  • The simplest approach would be to initialize `self.box` in `viewDidLoad` with correct initial value. – Losiowaty Sep 15 '16 at 16:26
  • I ended up "fixing" it by dropping the following line in before my crash line: if (self.box == (id)[NSNull null] || self.spayed.length == 0 ) self.box = @"N/A"; – Blair Warner Sep 15 '16 at 16:33