0

我正在尝试执行以下操作:

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);
}
4

1 回答 1

2

startNSDate 没有被保留,当你想访问它时,它已经被释放了,因此你试图访问垃圾指针

对你来说最简单的解决方案是

@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];
}
于 2012-09-11T23:00:06.557 回答