线程间的通信

1、一个线程传递数据给另一个线程;
2、一个线程执行完某个操作后,再转到另外一个线程执行操作
主线程又称UI线程,所有跟UI有关的操作,都放到主线程,其他操作放在子线程,

NSURL *url = [NSURL URLWithString:@"httpgdaga"];
//下载前的当前时间 CFTimeInterval begin
= CFAbsoluteTimeGetCurrent(); NSData *data = [NSData dataWithContentsOfURL:url];
//下载后的当前时间 CFTimeInterval end
= CFAbsoluteTimeGetCurrent(); NSLog(@"%f", end - begin); UIImage *image = [UIImage imageWithData:data]; self.imageView.image = image;
//计算时间差也可以用NSDate
NSDate *begin = [NSData date];
NSData *end = [NSDate date];
NSLog(@"%f", [end timeIntevelSinceData:begin]);






atomic与nonatomic
atomic原子属性,线程安全,调用setter方法是加锁,调用后解锁,但消耗大量资源,
nonatomic线程不安全,不会给setter方法加锁,适合内存小的移动设备
ios中尽量避免多线程抢夺同一数据,一般调用setter方法都是在主线程进行,所以一般涉及不到抢夺资源的情况,所以属性用nonatomic修饰
iOS建议
1、属性用nonatomic修饰
1、多个线程访问同一资源,会导致线程不安全
2、尽量将加锁、抢夺资源的工作放到服务器处理,减少手机的压力

 

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

 

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

}

 

 

- (void)download {

    NSURL *url = [NSURL URLWithString:@"httpgdaga"];

    NSData *data = [NSData dataWithContentsOfURL:url];

    UIImage *image = [UIImage imageWithData:data];

    [self performSelectorOnMainThread:@selector(xianshi:) withObject:image waitUntilDone:YES];

    //或者

    [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];

    [self.imageView performSelector:@selector(xianshi:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];

    

 

}

- (void)xianshi:(UIImage *)image {

    self.imageView.image = image;

}

 

posted on 2016-07-22 23:56  小艾的博客  阅读(129)  评论(0编辑  收藏  举报

导航