Creates a thread queue and puts the thread operations in the threads queue.
. h
//CoustomOperation.hNsoperation////Created by GG on 16/2/26. copyright©2016 years GG. All rights reserved. // #import <Foundation/ Foundation.h> #import <uikit/uikit.h> @interface coustomoperation: nsoperation//receive incoming Picture object @property (nonatomic,retain) uiimageview *imageview; When the class object is initialized, the picture is attempted to be passed into the class. -(Instancetype) Initwithimageview: (uiimageview *) ImageView; @end
. m
//Coustomoperation.mNsoperation//Created by GG on 16/2/26.copyright©2016 years GG. All rights reserved.//#import"CoustomOperation.h"#define KURL @"http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/ S38ga/rdgd/s38ga-rdgd-sel-201601?wid=848&hei=848&fmt=jpeg&qlt=80&op_sharpen=0&resmode= bicub&op_usm=0.5,0.5,0,0&iccembed=0&layer=comp&.v=1454777389943 "@implementationcoustomoperation-(Instancetype) Initwithimageview: (Uiimageview *) imageview{Self = [Super Init];if (Self) {Self. ImageView = ImageView; }ReturnSelf;} - (void) main{//create a new auto-free pool, because if it is a synchronous operation, the method can automatically access the auto-free pool of the main thread, and if it is performed asynchronously, it will not be able to access the auto-release pool to the main thread. @autoreleasepool {nslog (@ " Get the thread where the picture is%@ ", [nsthread CurrentThread]); nsdata *imagedata = [nsdata Datawithcontentsofurl:[nsurl Urlwithstring:kurl]; [[nsoperationqueue Mainqueue] addoperationwithblock:^{ NSLog (@ "Update UI on Thread%@", [nsthread CurrentThread]); self.imageview.image = [uiimage Imagewithdata:imagedata]; }]; }} @end
Viewcontroller.m
- (void)viewDidLoad{ [super viewDidLoad]; imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)]; [self.view addSubview:imageView]; CoustomOperation *coustomOperation = [[CoustomOperation alloc] initWithImageView:(UIImageView *)imageView]; NSOperationQueue *operationQueue = [NSOperationQueue new]; // [operationQueue addOperation:coustomOperation];}