Tutorial :NSDate assign problem


I would like to assign a date from one view controller to another

-(void) setCurrentDate:(NSDate newDate){      self.currentDate = newDate;      [self updateView];  }  

While debugging I see the currentDate value out of scope and the application crashes with EXC_BAD_ACCESS.

Any help will be appreciated.


You need to pass the pointer to date. Something like this:

-(void) setCurrentDate:(NSDate* newDate){      [self.currentDate release];      self.currentDate = newDate;      [self.currentDate retain];      [self updateView];  }  

Of course, your currentDate class variable should also be a NSDate pointer. It will be even better if you use a property instead of a custom made setter.


Besides that your setter should take NSDate by pointer (all class-type instances are passed by pointer in Objective-C), you are recursively calling the setter:
self.currentDate = foo results in [self setCurrentDate:foo] being called.

Correctly it should look e.g. like this (assuming a nonatomic, retain property):

- (void)setCurrentDate:(NSDate *)newDate {      if (currentDate != newDate) {          [currentDate release];          [newDate retain];          currentDate = newDate;          [self updateView];      }  }  

Alternatively name that method different from the setter so you can use the synthesized setter:

- (void)updateDate:(NSDate *)newDate {      self.currentDate = newDate;      [self updateView];  }  


Possibly, you need to retain newDate or copy it, if it's possible.

What I mean:

  1. You create newDate
  2. You call setCurrentDate
  3. You release newDate
  4. [self updateView] try to use it and fails because it is already released.

You also can try NSZombieEnabled to catch this kind of bugs.


In your method name, you use (NSDate date). You forgot to include the "*", which makes it a pointer. The correct code should be

-(void) setCurrentDate:(NSDate *newDate){ // Notice the star after NSDate        self.currentDate = newDate;      [self updateView];    }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »