您的位置:首页 > 移动开发 > Objective-C

object-c中创建线程的方法有哪些?在主线程中执行代码用什么方法?如果想要延时执行代码,用什么方法?

2014-05-12 14:19 465 查看
1.object-c中用NSThread创建线程的方法:

NSThread *oneThread=[[NSThread alloc]initWithTarget:self selector:@selector(sayMethod) object:nil];

[oneThread start];
  还可以是

[self performSelectorInBackground:@selector(sayMethod) withObject:nil];


也可以是

[NSThread detachNewThreadSelector:@selector(sayMethod) toTarget:self withObject:nil];

2.object-c中用NSOperation创建线程的方法

NSOperationQueue *queue=[[NSOperationQueue alloc]init];
[queue addOperationWithBlock:^{
[NSThread sleepForTimeInterval:3];
NSString *str=@"nice to meet you";
;
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
UILabel *onelabel=[[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
[self.view addSubview:onelabel];
onelabel.text=str;
}];
}];
3.object-c中用GCD创建线程的方法
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[NSThread sleepForTimeInterval:3];
NSString *str=@"nice to meet you";
NSLog(@"%@",str);
dispatch_async(dispatch_get_main_queue(), ^{
UILabel *onelabel=[[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
[self.view addSubview:onelabel];
onelabel.text=str;
});
});
NSOperationQueue
 gives finer control with what you want to do. You can create dependencies between the two operations (download and save to database). To pass the data between one block and the other, you
can assume for example, that a 
NSData
 will be coming from the server so:

block 代码端这个还不是很懂

__block NSData *dataFromServer = nil;
NSBlockOperation *downloadOperation = [[NSBlockOperation alloc] init];
__weak NSBlockOperation *weakDownloadOperation = downloadOperation;

[weakDownloadOperation addExecutionBlock:^{
// Download your stuff
// Finally put it on the right place:
dataFromServer = ....
}];

NSBlockOperation *saveToDataBaseOperation = [[NSBlockOperation alloc] init];
__weak NSBlockOperation *weakSaveToDataBaseOperation = saveToDataBaseOperation;

[weakSaveToDataBaseOperation addExecutionBlock:^{
// Work with your NSData instance
// Save your stuff
}];

[saveToDataBaseOperation addDependency:downloadOperation];

[myQueue addOperation:saveToDataBaseOperation];
[myQueue addOperation:downloadOperation];

在主线程中执行代码用什么方法?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 创建多线程
相关文章推荐