Here's a way to do it that keeps close to your existing structure using NSThread:
@interface MyThread : NSThread
@end
@implementation MyThread
-(void)main
{
NSDate * when = [ NSDate date ] ;
for ( int battery = 1000; battery >= 0; battery -= 1 )
{
when = [ NSDate dateWithTimeInterval:1.0 sinceDate:when ] ;
[ NSThread sleepUntilDate:when ] ;
[ [ NSThread mainThread ] perform:^{
[batteryLevel setProgress:(CGFloat)battery / 10.0 animated:YES];
batteryLevelLabel.text = [NSString stringWithFormat:@"Battery Level: %f%%", (CGFloat)battery / 10.0 ];
}];
}
}
@end
helper category:
@implementation NSThread (Perform)
-(void)_perform:(void(^)())block
{
block() ;
}
-(void)perform:(void(^)())block
{
BOOL wait = [ NSThread currentThread ] == self ;
[ self performSelector:@selector( _perform: ) onThread:self withObject:[ block copy ] waitUntilDone:wait ] ;
}
@end
Then start your timer with NSThread * thread = [ [ MyThread alloc ] init ] ; [ thread start ] ;
Probably easier to just rework your app to use a standard NSTimer + callback structure...
(I also did one using GCD to see what it looks like:
dispatch_queue_t q = dispatch_queue_create( NULL, NULL ) ;
dispatch_async( q, ^{
NSDate * when = [ NSDate date ] ;
for ( int battery = 1000; battery >= 0; battery -= 1 )
{
dispatch_sync( dispatch_get_main_queue(), ^{
[batteryLevel setProgress:(CGFloat)battery / 10.0 animated:YES];
batteryLevelLabel.text = [NSString stringWithFormat:@"Battery Level: %f%%", (CGFloat)battery / 10.0 ];
}) ;
when = [ NSDate dateWithTimeInterval:1.0 sinceDate:when ] ;
[ NSThread sleepUntilDate:when ] ;
}
}) ;
(But I don't think it's guaranteed that different queues are on different threads)