1. 程式人生 > >iOS NSThread 多執行緒載入網路圖片

iOS NSThread 多執行緒載入網路圖片

.m
定義圖片連結

// 圖片連結
#define KURL @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497938913914&di=73a53411ef5eb05285e674064cf26ccf&imgtype=0&src=http%3A%2F%2Fimg4.duitang.com%2Fuploads%2Fitem%2F201508%2F10%2F20150810164747_cZRKm.jpeg"

定義屬性 – 圖片框(展示圖片)

// 定義屬性
@property (nonatomic
,strong) UIImageView *imgView;

在 viewDidLoad 中初始化圖片框,使用 NSThread 多執行緒方法

- (void)viewDidLoad {
    [super viewDidLoad];

    // 初始化圖片框
    self.imgView = [[UIImageView alloc] initWithFrame:self.view.frame];

    self.imgView.backgroundColor = [UIColor magentaColor];

    [self.view addSubview:self.imgView
]; // 使用多執行緒的類方法 [NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:KURL]; }

實現 多執行緒的響應事件

// 實現多執行緒的響應事件
-(void)downloadImage:(NSString *)url
{
    // 建立物件
    NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];

    UIImage *img = [[UIImage alloc] initWithData:data];

    self.imgView.image = img;

}

相關推薦

no