ios 中的定时器功能

来源:互联网 发布:网络天才中文版下载app 编辑:程序博客网 时间:2024/06/03 23:05

在Object-C中,有三种方法可以实现定时器的功能。

1 使用NSObject对象的performSelector:withObject:afterDelay:的方法。
2 使用GCD的Block Objects方法。
3 使用GCD的C Functions方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (void) printString:(NSString *)paramString
{ 
    NSLog(@"%@", paramString);
}


- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    [self performSelector:@selector(printString:) withObject:@"Grand Central Dispatch" afterDelay:3.0];

    self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor]
    [self.window makeKeyAndVisible];
    return YES;
}

使用GCD的dispatch_after方法和dispatch_after_f方法。
第一个方法三个参数:Delay in nanoseconds,Dispatch queue,Block object
第二个方法四个参数:Delay in nanoseconds,Dispatch queue,Context,C function

第一种方法的实现:

1
2
3
4
5
6
7
double delayInSeconds = 2.0;
dispatch_time_t delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_after(delayInNanoSeconds, concurrentQueue, ^(void)
{ 
    /* Perform your operations here */
});

第二种实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void processSomething(void *paramContext){
    /* Do your processing here */
    NSLog(@"Processing...")
}

- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    double delayInSeconds = 2.0;
    dispatch_time_t delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_after_f(delayInNanoSeconds, concurrentQueue,NULL, processSomething);
    self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}
0 0
原创粉丝点击