NSTimer的暂停与恢复

#import <Foundation/Foundation.h>   
  1.   
  2. @interface NSTimer (Pausing)   
  3.   
  4. - (NSMutableDictionary *)pauseDictionary;   
  5. - (void)pause;   
  6. - (void)resume;   
  7.   
  8. @end  

 

NSTimer+Pausing.m

 

#import "NSTimer+Pausing.h"  
  1.   
  2. NSString *kIsPausedKey = @"IsPaused Key";   
  3. NSString *kRemainingTimeIntervalKey = @"RemainingTimeInterval Key";   
  4.   
  5. @implementation NSTimer (Pausing)   
  6.   
  7. - (NSMutableDictionary *)pauseDictionary {   
  8.     static NSMutableDictionary *globalDictionary = nil;   
  9.        
  10.     if(!globalDictionary)   
  11.         globalDictionary = [[NSMutableDictionary alloc] init];   
  12.        
  13.     if(![globalDictionary objectForKey:[NSNumber numberWithInt:(int)self]]) {   
  14.         NSMutableDictionary *localDictionary = [[[NSMutableDictionary alloc] init] autorelease];   
  15.         [globalDictionary setObject:localDictionary forKey:[NSNumber numberWithInt:(int)self]];   
  16.     }   
  17.        
  18.     return [globalDictionary objectForKey:[NSNumber numberWithInt:(int)self]];   
  19. }   
  20.   
  21. - (void)pause {   
  22.     if(![self isValid])   
  23.         return;   
  24.        
  25.     NSNumber *isPausedNumber = [[self pauseDictionary] objectForKey:kIsPausedKey];   
  26.     if(isPausedNumber && YES == [isPausedNumber boolValue])   
  27.         return;   
  28.        
  29.     NSDate *now = [NSDate date];   
  30.     NSDate *then = [self fireDate];   
  31.     NSTimeInterval remainingTimeInterval = [then timeIntervalSinceDate:now];   
  32.        
  33.     [[self pauseDictionary] setObject:[NSNumber numberWithDouble:remainingTimeInterval] forKey:kRemainingTimeIntervalKey];   
  34.        
  35.     [self setFireDate:[NSDate distantFuture]];   
  36.     [[self pauseDictionary] setObject:[NSNumber numberWithBool:YES] forKey:kIsPausedKey];   
  37. }   
  38.   
  39. - (void)resume {   
  40.     if(![self isValid])   
  41.         return;   
  42.        
  43.     NSNumber *isPausedNumber = [[self pauseDictionary] objectForKey:kIsPausedKey];   
  44.     if(!isPausedNumber || NO == [isPausedNumber boolValue])   
  45.         return;   
  46.        
  47.     NSTimeInterval remainingTimeInterval = [[[self pauseDictionary] objectForKey:kRemainingTimeIntervalKey] doubleValue];   
  48.        
  49.     NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:remainingTimeInterval];   
  50.        
  51.     [self setFireDate:fireDate];   
  52.     [[self pauseDictionary] setObject:[NSNumber numberWithBool:NO] forKey:kIsPausedKey];   
  53. }   
  54.   
  55. @end  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值