2015-08-25 137 views
-1

我有下面。NSDate抛出BAD_EXCESS为什么?

@interface MyViewController() { 
    NSDate *myCurrentDate; 
} 

@implementation MyViewController 

-(void)viewDidLoad { 
    [super viewDidLoad]; 
    myCurrentDate = [NSDate date]; 
} 


- (IBAction) prevAction:(id)sender { 
    NSLog(@"myCurrentDate===%@", myCurrentDate); // here it says 
    myCurrentDate = [myCurrentDate dateByAddingTimeInterval:60*60*24*-1]; 
    [self formatDateAndPostOnButton]; 
} 

当我尝试如下打印当前的日期,它崩溃说BAD_EXCESS

NSLog(@"myCurrentDate===%@", myCurrentDate); 

下面是相同的屏幕截图。

enter image description here

我不会在我的项目中使用ARC

任何想法是什么问题?

+0

这些是对mCurrentDate的唯一引用吗?或者你还在哪里使用它。在这些代码行中,我没有看到任何缺陷。 –

+0

您是否通过逐步调试的方式进行了重复检查,确定该异常真的在这条线上。 –

+0

@HermannKlecker:我有上一个和下一个按钮...我更新变量myCurrentDate然后我更新显示的标签... –

回答

2

由于您没有使用ARC,因此保留对象的最简单方法是使用生成的setter/getters。

相反的:

@interface MyViewController() { 
    NSDate *myCurrentDate; 
} 

使

@interface MyViewController() 
@property(nonatomic, retain) NSDate* myCurrentDate; 
@end 

所以它将继续保留NSDate。当自动释放池耗尽时,您的NSDate被取消分配。

您需要但使用所提供的getter/setter方法,:

self.myCurrentDate = [self.myCurrentDate dateByAddingTimeInterval:60*60*24*-1]; 

反正我会建议开始使用ARC,使您的生活更简单,避免奇怪的内存崩溃。

+0

我也试过,仍存在同样的问题。 –

+0

您无法将属性添加到接口变量块中。 –

+0

这解决了问题...谢谢... –

相关问题