views:

55

answers:

4

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.

A: 

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.

Pablo Santa Cruz
That would recursively call the setter.
Georg Fritzsche
Thanks, this correct, I am already using a property with synthize and release as appropiate.
Mohammed
@Mohammed: Have you tested this before accepting? This will result in `-setCurrentDate:` being called recursively and finally crash with an `EXC_BAD_ACCESS` or similar.
Georg Fritzsche
Agreed - with self.currentDate you are calling the setter for currentDate, which is overridden by the method here, setCurrentDate:. It is infinite recursion.
Rab
A: 

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.

Alexander Babaev
the currentDate member is created in the viewDidLoad event and retained currentDate = [[[NSDate alloc] initWithTimeIntervalSinceNow:0] retain];it is also synthizedI am totally fed up because everything looks correct.
Mohammed
A: 

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

}
HiGuy Smith
Thanks, I forgot it in the question, but it is correct in the code
Mohammed
That would also recursively call the setter.
Georg Fritzsche
+2  A: 

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