Friday, November 12, 2010

NSDate from UIDatePicker


BuschyBoy is offline
I have one UIDatePicker but it sets two different things. These two things are controlled by a Segmented controller. If it's on one side you're setting one date and if it's on the other side you're setting a different date. What I want it to do is save the date when you change the segmented controller. So first I have to save those dates. So when the datepicker is changed here is what is called:
Code:
-(void) pickerChangedDate:(id)sender {
 if([segmentedControl selectedSegmentIndex] == 0) {
  NSDate *aDate = [[NSDate alloc] init];
  aDate = [datePicker date];
  dateOne = aDate;
  [aDate release];
 } else {
  NSDate *aDate = [[NSDate alloc] init];
  aDate = [datePicker date];
  dateTwo = aDate;
  [aDate release];
 }      
}
So what I'm doing here is seeing which side needs to be set. When that side is determined I go ahead and try and save it as dateOne or dateTwo which are NSDate properties. This caused no errors but this did. This is what's called when the segmented controller changes:

Code:
-(void) segmentedChanged:(id)sender {
 if([segmentedControl selectedSegmentIndex] == 0) {
  [datePicker setDate:dateOne animated:YES];
 } else {
  [datePicker setDate:dateTwo animated:YES];
 } 
}
Any ideas as to why this would cause a crash?
BuschyBoy is offline  Reply With Quote

Default

You don't have a clear understanding of Cocoa memory management.

Code:
NSDate *aDate = [[NSDate alloc] init];
  aDate = [datePicker date];
  dateOne = aDate;
  [aDate release];
In these four lines you alloc/init a NSDate object and assign it to a local variable. On the next line you assign a different, NSDate instance to that local variable, leaking the first date. On the third line you assign the local variable to your ivar but it isn't retained. On the fourth line you release the local date variable and the ivar at the same time, even though you never retained it.

Try this: self.dateOne = [datePicker date];

Reread the memory management guide and the description of properties in the Obj-C 2.0 guide.

No comments:

Post a Comment

Followers