开发者

Create Time counter with Objective-C

I'm new int the objective-c and I'm trying to create a time counter, but when I start the start method, the update method is only one time executed and then I get in the console:

2010-12-11 14:11:45.080 StatusBarApp[10037:a0f] Break down: 0min 0hours 0days 0moths
Program received signal:  “EXC_BAD_ACCESS”.
sharedlibrary apply-load-rules all

I really don't understand where the problem is. Here's my code:

- (void)start:(id)sender {
     recordDate = [NSDate date];
     _timer = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self                 
     selector:@selector(updateTime:) userInfo:nil repeats:YES];
     [_timer fire];
 }


  - (void)stop:(id)sender {
       [statusItem setTitle:@""];
       [_timer invalidate];
           [_timer release];
}
   - (IBAction)updateTime:(id)sender {
    // The time interval 

    // Get the system calendar
    NSCalendar *sysCalendar = [NSCalendar currentCalendar];

    // Create the NSDates
    NSDate* date1 = [[NSDate alloc] init];
    // Get conversion to months, days, hours, minutes
    unsigned int flags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit |   NSMonthCalendarUnit;
     NSDateComponents* breakdownInfo = [sysCalendar components:flags fromDate:date1   toDate:recordDate  options:0];
     NSLog(@"Break down: %dmin %dhours %ddays %dmoths",[breakdownInfo minute],  [breakdownInfo hour], [breakdownInfo day], [breakdownInfo month]);
     [date1 release];
     [statusItem setTitle:[NSString stringWithFormat:@" %dmin %dhours %ddays  %dmot开发者_如何转开发hs",[breakdownInfo minute], [breakdownInfo hour], [breakdownInfo day], [breakdownInfo month]]];
   }


Your problem is that [NSDate date] returns an autoreleased date. This is fine for the first run of your timer, since you call fire on the timer before the end of the method that recordDate was initialised.

You need to retain recordDate for it to live long enough to survive another reference to it in the subsequent timer firings.

Autoreleased objects are released by the framework at the end of each run loop iteration. You can never reliably know when the run loop will end so you can only be safe in the assumption that autoreleased objects are safe to use up until the end of the method that they were autoreleased in.

adding recordDate = [[NSDate date] retain]; to your code should fix your problem.

But don't forget that now you have retained your recordDate object, you need to release it at some point in the future - in the stop: method would seem like a good place to do this.

Finally, after releasing your recordDate object, you should assign nil to the pointer to prevent any 'dangling pointer' problems.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜