-
- (void) doCalculation{
/* Do your calculation here */
}
-
- (void) calculationThreadEntry{
@autoreleasepool {
NSUInteger counter = 0;
while ([[NSThread currentThread] isCancelled] == NO){[self doCalculation];counter++;
if (counter >= 1000){break;}
}}
}
-
- (BOOL) application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
/* Start the thread */
-
//这里用NSThread生成一个新的线程,calculationThreadEntry这个方法,在新的线程中执行。
-
//其中这里需要注意的一点就是,calculationThreadEntry中得操作要放在自动释放池中进行。
-
[NSThread detachNewThreadSelector:@selector(calculationThreadEntry)
toTarget:selfwithObject:nil];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
-
}
而如果我们要用GCD做同样的工作,则不用显得如此繁琐
dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
size_t numberOfIterations
=
1000;
dispatch_async(queue, ^(void) {dispatch_apply(numberOfIterations, queue, ^(size_t iteration){
-
/* Perform the operation here */
});});
妹的,csdn太难用了
本文通过对比Objective-C中的两种线程管理方式——NSThread和Grand Central Dispatch (GCD),展示了如何利用GCD简化重复任务的执行过程。具体演示了在iOS应用启动时创建并运行一个执行1000次迭代计算的后台线程。
646

被折叠的 条评论
为什么被折叠?



