NSTimer的暂停与恢复

NSTimer+Pausing.h

 

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

 

NSTimer+Pausing.m

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值