Objective-C-NSObject类的线程方法

  1. 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;
}


你可能感兴趣的:(多线程)