views:

225

answers:

1

Before I begin I'll freely admit it's something in my code but it's not blatantly obvious what's causing it.

I'm storing one boolean and four NSDate objects in NSUserDefaults. I have a view that loads the information into controls: boolean into a switch and the 4 date values are loaded as the label on 4 buttons as formatted values. If the user clicks on a button I switch to a new view with a UIDatePicker that is preloaded with the full date from NSUserDefaults based on the button that was clicked. The 2nd view has two buttons: cancel and set. If you choose cancel we switch back to the first view. If you choose set the value from the UIDatePicker is stored in NSUserDefaults, the chosen button's label is updated, and we switch back to the first view.

I can consistently crash the application by clicking a button and then click cancel three times in a row, and then clicking the button a fourth time. It crashes in objc_msgSend when retrieving the value out of NSUserDefaults.

Here's the 3 functions involved.

  - (IBAction) buttonPressed:(id)sender {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDate *buttonDate;

    switch ([sender tag]) {
     case 1000:
      pressedString = kStartTime1Key;
      pressedButton = start1;
      break;
     case 1001:
      pressedString = kEndTime1Key;
      pressedButton = end1;
      break;
     case 1002:
      pressedString = kStartTime2Key;
      pressedButton = start2;
      break;
     case 1003:
      pressedString = kEndTime2Key;
      pressedButton = end2;
      break;
     default:
      break;
    }

    buttonDate = [defaults objectForKey:pressedString];
    if (buttonDate == nil) buttonDate = [NSDate date];
    [datePicker setDate:buttonDate animated:NO];
    [buttonDate release];

    self.view = datePickerView;
}

- (IBAction) savePressed {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDate *selected = [datePicker date];

    [defaults setObject:selected forKey:pressedString];
    [pressedButton setTitle:[self parseDate:selected] forState:UIControlStateNormal];

    self.view = settingsView;
}

- (IBAction) cancelPressed {
    self.view = settingsView;
}

Being an iPhone and Obj-C newbie, I'm sure there are better ways to do things, I'm open to suggestions.

A: 

[buttonDate release];

You can't release something you didn't allocate or retain.

newacct
Awesome! Removing [buttonDate release] definitely seems to have done it.
SauerC