標籤:property jsb super target load 進位 主線程 顯示 url
一、簡單說明
線程間通訊:在1個進程中,線程往往不是孤立存在的,多個線程之間需要經常進行通訊
線程間通訊的體現
1個線程傳遞資料給另1個線程
在1個線程中執行完特定任務後,轉到另1個線程繼續執行任務
線程間通訊常用方法
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
線程間通訊樣本 – 圖片下載
代碼1:
[objc] view plain copy
- //
- // YYViewController.m
- // 06-NSThread04-線程間通訊
- //
- // Created by apple on 14-6-23.
- // Copyright (c) 2014年 itcase. All rights reserved.
- //
-
- #import "YYViewController.h"
- @interface YYViewController ()
- @property (weak, nonatomic) IBOutlet UIImageView *iconView;
- @end
-
- @implementation YYViewController
-
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- }
-
- -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- {
-
- // 在子線程中調用download方法下載圖片
- [self performSelectorInBackground:@selector(download) withObject:nil];
- }
-
-
-
- -(void)download
- {
- //1.根據URL下載圖片
- //從網路中下載圖片
- NSURL *urlstr=[NSURL URLWithString:@"fdsf"];
-
- //把圖片轉換為二進位的資料
- NSData *data=[NSData dataWithContentsOfURL:urlstr];//這一行操作會比較耗時
-
- //把資料轉換成圖片
- UIImage *image=[UIImage imageWithData:data];
-
- //2.回到主線程中設定圖片
- [self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO];
- }
-
-
-
- //設定顯示圖片
- -(void)settingImage:(UIImage *)image
- {
- self.iconView.image=image;
- }
-
- @end
代碼2:
[objc] view plain copy
- //
- // YYViewController.m
- // 06-NSThread04-線程間通訊
- //
- // Created by apple on 14-6-23.
- // Copyright (c) 2014年 itcase. All rights reserved.
- //
-
- #import "YYViewController.h"
- #import <NSData.h>
-
- @interface YYViewController ()
- @property (weak, nonatomic) IBOutlet UIImageView *iconView;
- @end
-
- @implementation YYViewController
-
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- }
-
-
- -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- {
- // 在子線程中調用download方法下載圖片
-
- [self performSelectorInBackground:@selector(download) withObject:nil];
- }
-
-
- -(void)download
- {
-
- //1.根據URL下載圖片
- //從網路中下載圖片
- NSURL *urlstr=[NSURL URLWithString:@"fdsf"];
-
- //把圖片轉換為二進位的資料
- NSData *data=[NSData dataWithContentsOfURL:urlstr];//這一行操作會比較耗時
-
- //把資料轉換成圖片
- UIImage *image=[UIImage imageWithData:data];
-
- //2.回到主線程中設定圖片
- //第一種方式
- // [self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO];
-
- //第二種方式
- // [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];
-
- //第三種方式
- [self.iconView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
- }
-
-
- //設定顯示圖片
- //-(void)settingImage:(UIImage *)image
- //{
- // self.iconView.image=image;
- //}
-
- @end
iOS開發多線程篇—線程間的通訊