Objective-C中的定时器功能

本文介绍了在Objective-C中实现定时器功能的三种方法:使用NSObject的performSelector方法、使用GCD的BlockObjects方法及CFunctions方法。通过具体示例展示了如何使用这些方法来延时执行任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章参考地址:http://doandroid.info/object-c中的定时器功能/


在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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值