NSTimer的暂停与恢复

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-1 15:22   11   0

NSTimer+Pausing.h

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

NSTimer+Pausing.m

Ios代码 收藏代码
  1. #import "NSTimer+Pausing.h"
  2. NSString *kIsPausedKey = @"IsPaused Key";
  3. NSString *kRemainingTimeIntervalKey = @"RemainingTimeInterval Key";
  4. @implementation NSTimer (Pausing)
  5. - (NSMutableDictionary *)pauseDictionary {
  6. static NSMutableDictionary *globalDictionary = nil;
  7. if(!globalDictionary)
  8. globalDictionary = [[NSMutableDictionary alloc] init];
  9. if(![globalDictionary objectForKey:[NSNumber numberWithInt:(int)self]]) {
  10. NSMutableDictionary *localDictionary = [[[NSMutableDictionary alloc] init] autorelease];
  11. [globalDictionary setObject:localDictionary forKey:[NSNumber numberWithInt:(int)self]];
  12. }
  13. return [globalDictionary objectForKey:[NSNumber numberWithInt:(int)self]];
  14. }
  15. - (void)pause {
  16. if(![self isValid])
  17. return;
  18. NSNumber *isPausedNumber = [[self pauseDictionary] objectForKey:kIsPausedKey];
  19. if(isPausedNumber && YES == [isPausedNumber boolValue])
  20. return;
  21. NSDate *now = [NSDate date];
  22. NSDate *then = [self fireDate];
  23. NSTimeInterval remainingTimeInterval = [then timeIntervalSinceDate:now];
  24. [[self pauseDictionary] setObject:[NSNumber numberWithDouble:remainingTimeInterval] forKey:kRemainingTimeIntervalKey];
  25. [self setFireDate:[NSDate distantFuture]];
  26. [[self pauseDictionary] setObject:[NSNumber numberWithBool:YES] forKey:kIsPausedKey];
  27. }
  28. - (void)resume {
  29. if(![self isValid])
  30. return;
  31. NSNumber *isPausedNumber = [[self pauseDictionary] objectForKey:kIsPausedKey];
  32. if(!isPausedNumber || NO == [isPausedNumber boolValue])
  33. return;
  34. NSTimeInterval remainingTimeInterval = [[[self pauseDictionary] objectForKey:kRemainingTimeIntervalKey] doubleValue];
  35. NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:remainingTimeInterval];
  36. [self setFireDate:fireDate];
  37. [[self pauseDictionary] setObject:[NSNumber numberWithBool:NO] forKey:kIsPausedKey];
  38. }
  39. @end
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP