views:

740

answers:

4
+1  Q: 

NSDate Problem

I have the following code below that is meant to change a class var called "today" forward or backward by one day. It will work one time but then after that it crashes. It will do the same no matter if I press the left button or right button. What am I doing wrong?

the var today is a class var initiated as .. today = [NSDate date]

Here is the method that crashes :

 (IBAction)changeDateByOne:(id)sender{

NSDate *newDay;
NSDate *currentDay = today;

NSTimeInterval secondsPerDay = 24 * 60 * 60;

if(sender == leftButton){
  newDay = [currentDay addTimeInterval:-secondsPerDay];

}else if(sender == rightButton) { 
  newDay = [currentDay addTimeInterval: secondsPerDay];


}

today = newDay;

}

+1  A: 

Maybe you need to say

today = [[NSDate date] retain]
sigjuice
+1  A: 

I think you need to retain the newDay object returned from the addTimeInterval method. You may also need to release today before you do the assignment at the end.

kwbeam
+5  A: 

Not only do you need to retain the date created, but you also need to release the existing value held by "today," otherwise you'll leak the old reference.

When initializing the instance, use:

today = [[NSDate date] retain];

I would change the last line to:

[today release];
today = [newDay retain];

And finally, in your dealloc method, add:

[today release];

before calling [super dealloc];

NilObject
+2  A: 

You need to read the memory management documentation. That’s here:

http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

If you’re adding or subtracting days, you might want to read this which is an alternative way of doing the same thing:

http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendricalCalculations.html#//apple_ref/doc/uid/TP40007836-SW1

Lastly, if something crashes, it’s often helpful to look at the back traces (and include them in your questions if you can’t figure it out for yourself). Memory management bugs are usually the problem if you see objc_msgSend (or one of its companions) in the trace.

Chris Suter