您的位置:首页 > 其它

NSTimer的暂停与恢复

2013-01-21 09:59 155 查看
#import <Foundation/Foundation.h> @interface NSTimer (Pausing) - (NSMutableDictionary *)pauseDictionary; - (void)pause; - (void)resume; @end

#import <Foundation/Foundation.h>

@interface NSTimer (Pausing)

- (NSMutableDictionary *)pauseDictionary;
- (void)pause;
- (void)resume;

@end


NSTimer+Pausing.m

#import "NSTimer+Pausing.h"

NSString *kIsPausedKey = @"IsPaused Key";
NSString *kRemainingTimeIntervalKey = @"RemainingTimeInterval Key";

@implementation NSTimer (Pausing)

- (NSMutableDictionary *)pauseDictionary {
static NSMutableDictionary *globalDictionary = nil;

if(!globalDictionary)
globalDictionary = [[NSMutableDictionary alloc] init];

if(![globalDictionary objectForKey:[NSNumber numberWithInt:(int)self]]) {
NSMutableDictionary *localDictionary = [[[NSMutableDictionary alloc] init] autorelease];
[globalDictionary setObject:localDictionary forKey:[NSNumber numberWithInt:(int)self]];
}

return [globalDictionary objectForKey:[NSNumber numberWithInt:(int)self]];
}

- (void)pause {
if(![self isValid])
return;

NSNumber *isPausedNumber = [[self pauseDictionary] objectForKey:kIsPausedKey];
if(isPausedNumber && YES == [isPausedNumber boolValue])
return;

NSDate *now = [NSDate date];
NSDate *then = [self fireDate];
NSTimeInterval remainingTimeInterval = [then timeIntervalSinceDate:now];

[[self pauseDictionary] setObject:[NSNumber numberWithDouble:remainingTimeInterval] forKey:kRemainingTimeIntervalKey];

[self setFireDate:[NSDate distantFuture]];
[[self pauseDictionary] setObject:[NSNumber numberWithBool:YES] forKey:kIsPausedKey];
}

- (void)resume {
if(![self isValid])
return;

NSNumber *isPausedNumber = [[self pauseDictionary] objectForKey:kIsPausedKey];
if(!isPausedNumber || NO == [isPausedNumber boolValue])
return;

NSTimeInterval remainingTimeInterval = [[[self pauseDictionary] objectForKey:kRemainingTimeIntervalKey] doubleValue];

NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:remainingTimeInterval];

[self setFireDate:fireDate];
[[self pauseDictionary] setObject:[NSNumber numberWithBool:NO] forKey:kIsPausedKey];
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: