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

Objective-C-NSObject类的线程方法

2016-03-03 00:00 477 查看
摘要: oc中,NSObject 对象的 线程

demo,在iOS中NSObject 对象的 线程

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//子线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(createThread:) object:@"first"];
[thread start];
//子线程
[NSThread detachNewThreadSelector:@selector(createThread:) toTarget:self withObject:@"second"];
//子线程,后台
[self performSelectorInBackground:@selector(createThread:) withObject:@"thrid"];
//主线程
[self performSelector:@selector(createThread:) withObject:@"forth"];
//主线程,因为onThread:[NSThread currentThread]
[self performSelector:@selector(createThread:) onThread:[NSThread currentThread] withObject:@"fifth" waitUntilDone:NO];//改变yes,no
NSLog(@"---fifth:Done---");
}

- (void) createThread:(NSString *) who
{
NSLog(@"%@:%@",who, [NSThread currentThread]);
}

output:



2.线程间通信

子线程加载数据,福线程更新UI

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[ self performSelectorInBackground:@selector(downloadImage:) withObject:@"http://www.sinaimg.cn/qc/photo_auto/photo/34/78/6713478/6713478_src.jpg" ];
}

- (void) downloadImage:(NSString *) urlStr
{
NSLog(@"downLoading, thread is:%@", [NSThread currentThread]);
NSURL *url = [NSURL URLWithString:urlStr];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
//perform.... 执行完 前面的操作后(指令)才会执行 updateUi
[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
//    [self updateUI:image];
}

- (void) updateUI:(UIImage *)image
{
NSLog(@"updateUI:%@", [NSThread currentThread]);
self.testImgView.image = image;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程