A simple test --
- (void)viewDidLoad
{
[super viewDidLoad];
date2 = [NSDate dateWithTimeIntervalSinceNow:3];
myTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(timerFires)
userInfo:nil
开发者_StackOverflow repeats:YES];
}
- (void)timerFires{
date1 = [NSDate date];
NSTimeInterval timeBetween = [date1 timeIntervalSinceDate:date2];
NSLog(@"follow: %f", timeBetween);
}
It cause an "EXC_BAD_ACCESS" error in "timerFires"
Thread 1: Program received signal: "EXC_BAD_ACCESS".
I have declared 'date1' 'date2' and 'myTimer' in .h file.
It seems -(void)timerFires cannot got the value of 'date2'. Could you help me fix it please!
i'm guessing that your date variables are not staying around because you've never explicitly retained them. [NSDate dateWithTimeIntervalSinceNow:3] returns an autoreleased object. are you declaring the date instance variables as properties that are retained and synthesizing their getters and setters? for example, in your interface file:
@interface MyClass {
NSDate *date1;
NSDate *date2;
}
@property (nonatomic, retain) NSDate *date1;
@property (nonatomic, retain) NSDate *date2;
then in your implementation file:
@implementation
@synthesize date1, date2
then you should access them using self so they are properly retained:
self.date2 = [NSDate dateWithTimeIntervalSinceNow:3];
On doing date2 = [NSDate dateWithTimeIntervalSinceNow:3];
, you are assigning an autoreleased object to date2
. This is getting released before the timer fires. You will have to retain
the object if you want to use it elsewhere. So do this –
date2 = [[NSDate dateWithTimeIntervalSinceNow:3] retain];
Remember, since you are retaining this you will need to release it afterwards.
精彩评论