我正在尝试执行以下操作:
1)用户点击按钮开始,它会运行startTimer
方法,该方法会设置新的[NSDate date]
。
2)用户点击按钮停止它会运行stopTimer
方法,该方法会检索[NSDate date]
值。
我不能让第2步工作。我已将其设置在.h
文件中。如果我将start方法中的代码复制到stop方法中,则可以正常工作。所以,我可以设置[NSDate date]
。但是,这不是我想要的。我希望能够在startTimer
方法中进行设置。我该怎么做?
.h文件
@interface StartTest : UIViewController {
IBOutlet UILabel *timer;
NSDate *startNSDate;
NSDate *start;
}
- (IBAction)startTimer;
- (IBAction)stopTimer;
- (NSDate *)setStart;
- (NSDate *)getStart;
@end
.m文件:
@implementation Ash
- (IBAction)startTimer {
startNSDate = [NSDate date];
}
- (IBAction)stopTimer{
start = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
NSString *stringFromDate = [formatter stringFromDate:startNSDate]; // <<< this is where it fails
NSLog(@"stringfromdate: %@", stringFromDate);
}
答案 0 :(得分:2)
startNSDate没有保留,当你想要访问它时,它已经被dealloc'd,因此你试图访问垃圾指针
最简单的解决方案是
@interface StartTest : UIViewController {
IBOutlet UILabel *timer;
NSDate *startNSDate;
NSDate *start;
}
@property (nonatomic, strong) NSDate* startNSDate;
- (IBAction)startTimer;
- (IBAction)stopTimer;
- (NSDate *)setStart;
- (NSDate *)getStart;
@end
@implementation Ash
- (IBAction)startTimer {
self.startNSDate = [NSDate date];
}
- (IBAction)stopTimer{
start = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
// this is where it fails, the reason being that startNSDate isn't retained
// and by this line, it's already dealloc'd, hence you're trying to access
// garbage pointer
NSString *stringFromDate = [formatter self.startNSDate];
NSLog(@"stringfromdate: %@", stringFromDate);
}
- (void)dealloc
{
self.startNSDate = nil;
[super dealloc];
}