NSDate crash with successive actions

拟墨画扇 提交于 2019-12-12 14:23:42

问题


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:


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




回答2:


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.




回答3:


Maybe you need to say

today = [[NSDate date] retain]



回答4:


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.



来源:https://stackoverflow.com/questions/992137/nsdate-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!