首页 > 代码库 > 多线程练习 -- 自定义NSOperation

多线程练习 -- 自定义NSOperation

LWTViewController.h

#import <UIKit/UIKit.h>@interface LWTViewController : UITableViewController@end
View Code

LWTViewController.m

////  LWTViewController.m//  多线程练习 -- 自定义NSOperation////  Created by apple on 14-6-25.//  Copyright (c) 2014年 lwt. All rights reserved.//#import "LWTViewController.h"#import "LWTAppModel.h"#import "LWTAppCell.h"#import "LWTDownloadOperation.h"@interface LWTViewController () <LWTDownloadOperationDelegate>@property (nonatomic, strong) NSArray *apps;@property (nonatomic, strong) NSOperationQueue *queue;@property (nonatomic, strong) NSMutableDictionary *operations;@property (nonatomic, strong) NSMutableDictionary *images;@end@implementation LWTViewController- (NSArray *)apps{    if (_apps == nil) {        NSString *path = [[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil];        NSArray *appArray = [NSArray arrayWithContentsOfFile:path];        NSMutableArray *models = [NSMutableArray arrayWithCapacity:appArray.count];        for (NSDictionary *dict in appArray) {            LWTAppModel *app = [LWTAppModel appWithDict:dict];            [models addObject:app];        }        _apps = [models copy];    }    return _apps;}- (NSOperationQueue *)queue{    if (_queue == nil) {        _queue = [[NSOperationQueue alloc] init];        _queue.maxConcurrentOperationCount = 2;    }    return _queue;}- (NSMutableDictionary *)operations{    if (_operations == nil) {        _operations = [NSMutableDictionary dictionary];    }    return _operations;}- (NSMutableDictionary *)images{    if (_images == nil) {        _images = [NSMutableDictionary dictionary];    }    return _images;}#pragma mark - 数据源方法- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    return self.apps.count;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    LWTAppCell *cell = [LWTAppCell appCellWithTableView:tableView];        LWTAppModel *app = self.apps[indexPath.row];        UIImage *image = self.images[app.icon];    if (image) {        cell.image = image;    }else{        cell.image = [UIImage imageNamed:@"btn_icon_xihuan_normal"];                if (!self.operations[app.icon]) {            LWTDownloadOperation *operation = [[LWTDownloadOperation alloc] init];            operation.indexPath = indexPath;            operation.url = app.icon;            operation.delegate = self;            [self.queue addOperation:operation];            self.operations[app.icon] = operation;        }    }        cell.app = app;                return cell;}#pragma mark - LWTDownloadOperationDelegate- (void)downloadOperation:(LWTDownloadOperation *)downloadOperation DidFinishDownload:(UIImage *)image{    if (image) {                self.images[downloadOperation.url] = image;        [self.tableView reloadRowsAtIndexPaths:@[downloadOperation.indexPath] withRowAnimation:UITableViewRowAnimationNone];    }        [self.operations removeObjectForKey:downloadOperation.url];}- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{    [self.queue setSuspended:YES];    NSLog(@"%d",self.queue.isSuspended);}- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{    [self.queue setSuspended:NO];    NSLog(@"%d",self.queue.isSuspended);}@end
View Code

LWTAppModel.h

////  LWTAppModel.h//  多线程练习 -- 自定义NSOperation////  Created by apple on 14-6-25.//  Copyright (c) 2014年 lwt. All rights reserved.//#import <Foundation/Foundation.h>@interface LWTAppModel : NSObject@property (nonatomic, copy) NSString *name;@property (nonatomic, copy) NSString *icon;@property (nonatomic, copy) NSString *download;- (instancetype)initWithDict: (NSDictionary *)dict;+ (instancetype)appWithDict : (NSDictionary *)dict;@end
View Code

LWTAppModel.m

////  LWTAppModel.m//  多线程练习 -- 自定义NSOperation////  Created by apple on 14-6-25.//  Copyright (c) 2014年 lwt. All rights reserved.//#import "LWTAppModel.h"@implementation LWTAppModel- (instancetype)initWithDict:(NSDictionary *)dict{    self = [super init];    if (self) {        [self setValuesForKeysWithDictionary:dict];    }    return self;}+ (instancetype)appWithDict:(NSDictionary *)dict{    return [[self alloc] initWithDict:dict];}@end
View Code

LWTAppCell.h

////  LWTAppCell.h//  多线程练习 -- 自定义NSOperation////  Created by apple on 14-6-25.//  Copyright (c) 2014年 lwt. All rights reserved.//#import <UIKit/UIKit.h>@class LWTAppModel;@interface LWTAppCell : UITableViewCell@property (nonatomic, strong) LWTAppModel *app;@property (nonatomic, strong) UIImage *image;+ (instancetype)appCellWithTableView : (UITableView *)tableView;@end
View Code

LWTAppCell.m

////  LWTAppCell.m//  多线程练习 -- 自定义NSOperation////  Created by apple on 14-6-25.//  Copyright (c) 2014年 lwt. All rights reserved.//#import "LWTAppCell.h"#import "LWTAppModel.h"@implementation LWTAppCell+ (instancetype)appCellWithTableView:(UITableView *)tableView{    NSString *ID = @"app";    LWTAppCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];    if (cell == nil) {        cell = [[LWTAppCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];    }    return cell;}- (void)setApp:(LWTAppModel *)app{    _app =app;    self.textLabel.text = _app.name;    self.detailTextLabel.text = _app.download;    self.imageView.image = self.image;    }@end
View Code

LWTDownloadOperation.h

////  LWTDownloadOperation.h//  多线程练习 -- 自定义NSOperation////  Created by apple on 14-6-25.//  Copyright (c) 2014年 lwt. All rights reserved.//#import <Foundation/Foundation.h>@class LWTDownloadOperation;@protocol LWTDownloadOperationDelegate <NSObject>@optional- (void)downloadOperation:(LWTDownloadOperation *)downloadOperation DidFinishDownload : (UIImage *)image;@end@interface LWTDownloadOperation : NSOperation@property (nonatomic, strong) NSString *url;@property (nonatomic, strong) NSIndexPath *indexPath;@property (nonatomic, weak) id<LWTDownloadOperationDelegate> delegate;@end
View Code

LWTDownloadOperation.m

////  LWTDownloadOperation.m//  多线程练习 -- 自定义NSOperation////  Created by apple on 14-6-25.//  Copyright (c) 2014年 lwt. All rights reserved.//#import "LWTDownloadOperation.h"@implementation LWTDownloadOperation- (void)main{    @autoreleasepool {        NSLog(@"%@",[NSThread currentThread]);        [NSThread sleepForTimeInterval:2.0];                if (self.isCancelled) return;        NSInteger interval = arc4random_uniform(8);        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(interval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{                    NSURL *url = [NSURL URLWithString:self.url];            NSData *data =http://www.mamicode.com/ [NSData dataWithContentsOfURL:url];            if (self.isCancelled) return ;            UIImage *image = [UIImage imageWithData:data];                        if (self.isCancelled) return;                        if ([self.delegate respondsToSelector:@selector(downloadOperation:DidFinishDownload:)]) {                dispatch_async(dispatch_get_main_queue(), ^{                    [self.delegate downloadOperation:self DidFinishDownload:image];                });            }                    });            }}@end
View Codea

apps.plist

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><array>    <dict>        <key>name</key>        <string>植物大战僵尸</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/LuckyMidPressed@2x.png</string>        <key>download</key>        <string>10311万</string>    </dict>    <dict>        <key>name</key>        <string>捕鱼达人2</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/userphoto_default_180.png</string>        <key>download</key>        <string>9982万</string>    </dict>    <dict>        <key>name</key>        <string>保卫萝卜</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/icon_163.png</string>        <key>download</key>        <string>8582万</string>    </dict>    <dict>        <key>name</key>        <string>找你妹</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/icon_kaixin.png</string>        <key>download</key>        <string>5910万</string>    </dict>    <dict>        <key>name</key>        <string>水果忍者</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/icon_qq.png</string>        <key>download</key>        <string>5082万</string>    </dict>    <dict>        <key>name</key>        <string>鳄鱼小顽皮</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/scene.png</string>        <key>download</key>        <string>3918万</string>    </dict>    <dict>        <key>name</key>        <string>神偷奶爸</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/icon_sina.png</string>        <key>download</key>        <string>3681万</string>    </dict>    <dict>        <key>name</key>        <string>时空猎人</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/icon_sohu.png</string>        <key>download</key>        <string>3645万</string>    </dict>    <dict>        <key>name</key>        <string>愤怒的小鸟</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/me@2x.png</string>        <key>download</key>        <string>3552万</string>    </dict>    <dict>        <key>name</key>        <string>滑雪大冒险</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/psb.png</string>        <key>download</key>        <string>3487万</string>    </dict>    <dict>        <key>name</key>        <string>爸爸去哪儿</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/icon_renren.png</string>        <key>download</key>        <string>3117万</string>    </dict>    <dict>        <key>name</key>        <string>我叫MT </string>        <key>icon</key>        <string>file:///Users/apple/Desktop/scene@2x.png</string>        <key>download</key>        <string>2386万</string>    </dict>    <dict>        <key>name</key>        <string>3D终极狂飙</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/QQ20140413-4@2x.png</string>        <key>download</key>        <string>2166万</string>    </dict>    <dict>        <key>name</key>        <string>杀手2</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/QQ20140413-5@2x.png</string>        <key>download</key>        <string>1951万</string>    </dict>    <dict>        <key>name</key>        <string>俄罗斯方块</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/175792428160@2x.png</string>        <key>download</key>        <string>1290万</string>    </dict>    <dict>        <key>name</key>        <string>刀塔传奇</string>        <key>icon</key>        <string>file:///Users/apple/Desktop/173890450691@2x.png</string>        <key>download</key>        <string>1249万</string>    </dict></array></plist>
View Code