主頁 >  其他 > ios基礎篇(十四)—— 操作依賴、操作快取池

ios基礎篇(十四)—— 操作依賴、操作快取池

2020-11-08 23:17:50 其他

一、NSOperation VS GCD

  • GCD
    • GCD是iOS4.0 推出的,主要針對多核cpu做了優化,是C語言的技術
    • GCD是將任務(block)添加到佇列(串行/并行/全域/主佇列),并且以同步/異步的方式執行任務的函式
    • GCD提供了一些NSOperation不具備的功能
      • 一次性執行
      • 延遲執行
      • 調度組
  • NSOperation
    • NSOperation是iOS2.0推出的,iOS4之后重寫了NSOperation
    • NSOperation將操作(異步的任務)添加到佇列(并發佇列),就會執行指定操作的函式
    • NSOperation里提供的方便的操作
      • 最大并發數
      • 佇列的暫定/繼續
      • 取消所有的操作
      • 指定操作之間的依賴關系(GCD可以用同步實作)

二、最大并發數

  • 什么是并發數

同時執行的任務數

比如,同時開3個執行緒執行3個任務,并發數就是3

  • 最大并發數的相關方法
- (NSInteger)maxConcurrentOperationCount;
- (void)setMaxConcurrentOperationCount:(NSInteger)cnt;
  • 執行的程序
  • 1、把操作添加到佇列self.queue addOperationWithBlock
  • 2、去執行緒池去取空閑的執行緒,如果沒有就創建執行緒
  • 3、把操作交給從執行緒池中取出的執行緒執行
  • 4、執行完成后,把執行緒再放回執行緒池中
  • 5、重復2,3,4知道所有的操作都執行完

佇列的暫停、取消、恢復

取消佇列的所有操作
- (void)cancelAllOperations;
提示:也可以呼叫NSOperation的- (void)cancel方法取消單個操作
暫停和恢復佇列
- (void)setSuspended:(BOOL)b; // YES代表暫停佇列,NO代表恢復佇列
- (BOOL)isSuspended;

搖獎機

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *lbl1;
@property (weak, nonatomic) IBOutlet UILabel *lbl2;
@property (weak, nonatomic) IBOutlet UILabel *lbl3;
@property (weak, nonatomic) IBOutlet UIButton *startButton;
//全域佇列
@property (nonatomic, strong) NSOperationQueue *queue;
@end

@implementation ViewController
//懶加載
- (NSOperationQueue *)queue {
    if (_queue == nil) {
        _queue = [NSOperationQueue new];
    }
    return _queue;
}
//點擊開始執行
- (IBAction)start:(UIButton *)sender {
    //當佇列中有操作的時候,不添加操作    
    if (self.queue.operationCount == 0) {
        //異步執行 添加操作
        [self.queue addOperationWithBlock:^{
            [self random];
        }];
        [self.startButton setTitle:@"暫停" forState:UIControlStateNormal];
        self.queue.suspended = NO;
    }else if(!self.queue.isSuspended) {
        //正在執行的時候,暫停
        //先把當前的操作執行完畢,暫停后續的操作
        self.queue.suspended = YES;
        [self.startButton setTitle:@"繼續" forState:UIControlStateNormal];
    }    
}
//隨機生成3個數字,顯示到label上
- (void)random {
    while (!self.queue.isSuspended) {
        [NSThread sleepForTimeInterval:0.05];
        //生成亂數     [0,10)  0-9
        int num1 = arc4random_uniform(10);
        int num2 = arc4random_uniform(10);
        int num3 = arc4random_uniform(10);
        //回到主執行緒上更新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            //給label賦值
            self.lbl1.text = [NSString stringWithFormat:@"%d",num1];
            self.lbl2.text = [NSString stringWithFormat:@"%d",num2];
            self.lbl3.text = [NSString stringWithFormat:@"%d",num3];            
        }];
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"%zd",self.queue.operationCount);
}

三、操作的優先級

  • 設定NSOperation在queue中的優先級,可以改變操作的執行優先級
- (NSOperationQueuePriority)queuePriority;
- (void)setQueuePriority:(NSOperationQueuePriority)p;
  • iOS8以后推薦使用服務質量 qualityOfService

監聽操作完成

  • 可以監聽一個操作的執行完畢
- (void (^)(void))completionBlock;
- (void)setCompletionBlock:(void (^)(void))block;
@interface ViewController ()
@property (nonatomic, strong) NSOperationQueue *queue;
@end

@implementation ViewController
//懶加載
- (NSOperationQueue *)queue{
    if (_queue == nil) {
        _queue = [NSOperationQueue new];
    }
    return _queue;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //操作1
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 20; i++) {
            NSLog(@"op1  %d",i);
        }
    }];
    //設定優先級最高
    op1.qualityOfService = NSQualityOfServiceUserInteractive;
    [self.queue addOperation:op1];    
    //等操作完成,執行  執行在子執行緒上
    [op1 setCompletionBlock:^{
        NSLog(@"============op1 執行完成========== %@",[NSThread currentThread]);
    }]; 
    //操作2
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 20; i++) {
            NSLog(@"op2  %d",i);
        }
    }];
    //設定優先級最低
    op2.qualityOfService = NSQualityOfServiceBackground;
    [self.queue addOperation:op2];
}
@end

四、操作依賴

  • NSOperation之間可以設定依賴來保證執行順序

比如一定要讓操作A執行完后,才能執行操作B,可以這么寫

[operationB addDependency:operationA]; // 操作B依賴于操作A

可以在不同queue的NSOperation之間創建依賴關系

模擬軟體升級程序:下載—解壓—升級完成

@interface ViewController ()
@property (nonatomic, strong) NSOperationQueue *queue;
@end
@implementation ViewController
- (NSOperationQueue *)queue {
    if (_queue == nil) {
        _queue = [NSOperationQueue new];
    }
    return _queue;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // 下載 - 解壓 - 升級完成
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"下載");
    }];    
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        [NSThread sleepForTimeInterval:2.0];
        NSLog(@"解壓");
    }];
    NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"升級完成");
    }];
    //設定操作間的依賴
    [op2 addDependency:op1];
    [op3 addDependency:op2];
    //錯誤,會發生回圈依賴,什么都不執行
//    [op1 addDependency:op3]; 
    //操作添加到佇列中
    [self.queue addOperations:@[op1,op2] waitUntilFinished:NO];
    //依賴關系可以夸佇列執行
    [[NSOperationQueue mainQueue] addOperation:op3];
}

案例-UITableView中顯示圖片

步驟1—資料模型準備

  • 把準備好的資料源(plist)轉換成我們使用方便的物件集合

    從字典型別自定系結屬性
  [obj setValuesForKeysWithDictionary:dict];

提供方法—---生成所有物件的一個集合

  + (NSArray *)appList;

搭建界面

  • UITabelViewController
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

把name和download都先顯示到界面上

同步方式下載圖片

  • 在cell生成的時候下載圖片
     //模擬網路延時
    [NSThread sleepForTimeInterval:0.5];

    NSURL *url = [NSURL URLWithString:appInfo.icon];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *img = [UIImage imageWithData:data];

問題:進入界面很慢,一滑動就卡

原因:同步方式去下載圖片的時候,系統無法很快執行界面渲染,俗稱“卡主執行緒”

問題:每次上拉下拉的時候都會重復下載圖片

ViewController.m

#import "ViewController.h"
#import "HMAppInfo.h"
@interface ViewController ()
@property (nonatomic, strong) NSArray *appInfos;
@end
//1 創建模型類,獲取資料,測驗
//2 資料源方法
//3 同步下載圖片
@implementation ViewController
//懶加載
- (NSArray *)appInfos {
    if (_appInfos == nil) {
        _appInfos = [HMAppInfo appInfos];
    }
    return _appInfos;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //1 測驗模型資料
//    NSLog(@"%@",self.appInfos);
}
//2 資料源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.appInfos.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //1 創建可重用的cell
    static NSString *reuseId = @"appInfo";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseId];
    }
    //2 獲取資料,給cell內部子控制元件賦值
    HMAppInfo *appInfo = self.appInfos[indexPath.row];    
    cell.textLabel.text = appInfo.name;
    cell.detailTextLabel.text = appInfo.download;    
    //同步下載圖片
    //模擬網速比較慢
    [NSThread sleepForTimeInterval:0.5];
    NSURL *url = [NSURL URLWithString:appInfo.icon];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *img = [UIImage imageWithData:data];
    cell.imageView.image = img;    
    //3 回傳cell
    return cell;
}
@end

HMAppInfo.h

@interface HMAppInfo : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, copy) NSString *download;
+ (instancetype)appInfoWithDic:(NSDictionary *)dic;
//獲取所有的模型資料
+ (NSArray *)appInfos;
@end

HMAppInfo.m

#import "HMAppInfo.h"
@implementation HMAppInfo
+ (instancetype)appInfoWithDic:(NSDictionary *)dic {
    HMAppInfo *appInfo = [[self alloc] init];
    //kvc給屬性賦值
    [appInfo setValuesForKeysWithDictionary:dic];
    return appInfo;
}
+ (NSArray *)appInfos{
    //加載plist
    NSString *path = [[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil];
    NSArray *array = [NSArray arrayWithContentsOfFile:path];    
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:10];
    //便利陣列的另一種方式
    [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //字典轉模型
        HMAppInfo *appInfo = [self appInfoWithDic:obj];
        [mArray addObject:appInfo];
    }];    
    //回傳  對可變陣列進行copy操作,變成不可變陣列
    return mArray.copy;
}
@end

異步方式下載圖片

  • 異步方式下載圖片
//異步加載網路圖片
    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
    }];
  • 問題1:圖片顯示不出,點擊才顯示
  • 原因:cell中的imageView是懶加載的,在初始化的時候圖片沒有指定,所以圖片大小為0x0
  • 解決:設定占位圖片

ViewController.m

#import "ViewController.h"
#import "HMAppInfo.h"
#import "HMAppInfoCell.h"
@interface ViewController ()
@property (nonatomic, strong) NSArray *appInfos;
//全域佇列
@property (nonatomic, strong) NSOperationQueue *queue;
@end
//1 創建模型類,獲取資料,測驗
//2 資料源方法
//3 同步下載圖片--如果網速比較慢,界面會卡頓
//4 異步下載圖片--圖片顯示不出來,點擊cell或者上下拖動圖片可以顯示
    //解決,使用占位圖片
@implementation ViewController
//懶加載
- (NSArray *)appInfos {
    if (_appInfos == nil) {
        _appInfos = [HMAppInfo appInfos];
    }
    return _appInfos;
}
- (NSOperationQueue *)queue {
    if (_queue == nil) {
        _queue = [NSOperationQueue new];
    }
    return _queue;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //1 測驗模型資料
//    NSLog(@"%@",self.appInfos);
}
//2 資料源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.appInfos.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //1 創建可重用的cell
    static NSString *reuseId = @"appInfo";
    HMAppInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
    if (cell == nil) {
        cell = [[HMAppInfoCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseId];
    }
    //2 獲取資料,給cell內部子控制元件賦值
    HMAppInfo *appInfo = self.appInfos[indexPath.row];    
    //cell內部的子控制元件都是懶加載的
    //當回傳cell之前,會呼叫cell的layoutSubviews方法
    cell.textLabel.text = appInfo.name;
    cell.detailTextLabel.text = appInfo.download;
    //設定占位圖片
    cell.imageView.image = [UIImage imageNamed:@"user_default"];
    //異步下載圖片
    //模擬網速比較慢
    [self.queue addOperationWithBlock:^{
        [NSThread sleepForTimeInterval:0.5];
        NSURL *url = [NSURL URLWithString:appInfo.icon];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *img = [UIImage imageWithData:data];        
        //主執行緒上更新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            cell.imageView.image = img;
        }];
    }];
    //3 回傳cell
    return cell;
}
@end

HMAppInfoCell.m

#import "HMAppInfoCell.h"
@implementation HMAppInfoCell
- (void)layoutSubviews {
    [super layoutSubviews];    
    NSLog(@"layoutSubviews");
}
@end
  • 問題2:頻繁滾動時,反復下載相同圖片
  • 解決:圖片快取,模型類中增加image的屬性

  • 問題3:頻繁滾動時,并且超出螢屏的圖片下載速度比較慢的情況,圖片可能錯位,并且圖片來回跳
  • 原因:cell的重用
  • 解決:當異步下載完成后,回到主執行緒重新加載對應的cell

ViewController.m

#import "ViewController.h"
#import "HMAppInfo.h"
#import "HMAppInfoCell.h"
@interface ViewController ()
@property (nonatomic, strong) NSArray *appInfos;
//全域佇列
@property (nonatomic, strong) NSOperationQueue *queue;
@end
//1 創建模型類,獲取資料,測驗
//2 資料源方法
//3 同步下載圖片--如果網速比較慢,界面會卡頓
//4 異步下載圖片--圖片顯示不出來,點擊cell或者上下拖動圖片可以顯示
    //解決,使用占位圖片
//5 圖片快取--把網路上下載的圖片,保存到記憶體
    //解決,圖片重復下載,把圖片快取到記憶體中,節省用戶的流量 (拿空間換取執行時間)
//6 解決圖片下載速度特別慢,出現的錯行問題,
    //當圖片下載完成之后,重新加載對應的cell
@implementation ViewController
//懶加載
- (NSArray *)appInfos {
    if (_appInfos == nil) {
        _appInfos = [HMAppInfo appInfos];
    }
    return _appInfos;
}
- (NSOperationQueue *)queue {
    if (_queue == nil) {
        _queue = [NSOperationQueue new];
    }
    return _queue;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //1 測驗模型資料
//    NSLog(@"%@",self.appInfos);
}
//2 資料源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.appInfos.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //1 創建可重用的cell
    static NSString *reuseId = @"appInfo";
    HMAppInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
    if (cell == nil) {
        cell = [[HMAppInfoCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseId];
    }
    //2 獲取資料,給cell內部子控制元件賦值
    HMAppInfo *appInfo = self.appInfos[indexPath.row];   
    //cell內部的子控制元件都是懶加載的
    //當回傳cell之前,會呼叫cell的layoutSubviews方法
    cell.textLabel.text = appInfo.name;
    cell.detailTextLabel.text = appInfo.download;    
    //判斷有沒有圖片快取
    if (appInfo.image) {
        NSLog(@"從快取加載圖片...");
        cell.imageView.image = appInfo.image;
        return cell;
    } 
    //設定占位圖片
    cell.imageView.image = [UIImage imageNamed:@"user_default"];    
    //異步下載圖片
    //模擬網速比較慢
    [self.queue addOperationWithBlock:^{
//        [NSThread sleepForTimeInterval:0.5];
        //模擬圖片下載速度慢
        if (indexPath.row > 9) {
            [NSThread sleepForTimeInterval:5];
        }        
        //下載圖片
        NSLog(@"下載網路圖片...");
        NSURL *url = [NSURL URLWithString:appInfo.icon];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *img = [UIImage imageWithData:data];        
        //快取圖片
        appInfo.image = img;        
        //主執行緒上更新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//            cell.imageView.image = img;
            //解決圖片顯示錯行
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }];
    }];
    //3 回傳cell
    return cell;
}
@end

操作快取池

  • 問題:由于滑動過快導致多次下載相同圖片
  • 解決:操作快取
  • 定義一個字典,把每次操作都放在里面,避免相同操作的出現
  NSMutableDictionary *operationCaches;
@interface ViewController ()
@property (nonatomic, strong) NSArray *appInfos;
//全域佇列
@property (nonatomic, strong) NSOperationQueue *queue;
//圖片的快取池
@property (nonatomic, strong) NSMutableDictionary *imageCache;
//下載操作快取池
@property (nonatomic, strong) NSMutableDictionary *downloadCache;
@end
//1 創建模型類,獲取資料,測驗
//2 資料源方法
//3 同步下載圖片--如果網速比較慢,界面會卡頓
//4 異步下載圖片--圖片顯示不出來,點擊cell或者上下拖動圖片可以顯示
    //解決,使用占位圖片
//5 圖片快取--把網路上下載的圖片,保存到記憶體--圖片存盤在模型物件中
    //解決,圖片重復下載,把圖片快取到記憶體中,節省用戶的流量 (拿空間換取執行時間)
//6 解決圖片下載速度特別慢,出現的錯行問題,
    //當圖片下載完成之后,重新加載對應的cell
//7 當收到記憶體警告,要清理記憶體,如果圖片存盤在模型物件中,不好清理記憶體
    //圖片的快取池
//8 當有些圖片下載速度比較慢,上下不停滾動的時候,會重復下載圖片,會浪費流量
    //判斷當前是否有對應圖片的下載操作,如果沒有添加下載操作,如果有不要重復創建操作
    //下載操作的快取池
@implementation ViewController
//懶加載
- (NSArray *)appInfos {
    if (_appInfos == nil) {
        _appInfos = [HMAppInfo appInfos];
    }
    return _appInfos;
}
- (NSOperationQueue *)queue {
    if (_queue == nil) {
        _queue = [NSOperationQueue new];
    }
    return _queue;
}
- (NSMutableDictionary *)imageCache {
    if (_imageCache == nil) {
        _imageCache = [NSMutableDictionary dictionaryWithCapacity:10];
    }
    return _imageCache;
}
- (NSMutableDictionary *)downloadCache {
    if (_downloadCache == nil) {
        _downloadCache = [NSMutableDictionary dictionaryWithCapacity:10];
    }
    return _downloadCache;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //1 測驗模型資料
//    NSLog(@"%@",self.appInfos);
}
//2 資料源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.appInfos.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //1 創建可重用的cell
    static NSString *reuseId = @"appInfo";
    HMAppInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
    if (cell == nil) {
        cell = [[HMAppInfoCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseId];
    }
    //2 獲取資料,給cell內部子控制元件賦值
    HMAppInfo *appInfo = self.appInfos[indexPath.row];
    
    //cell內部的子控制元件都是懶加載的
    //當回傳cell之前,會呼叫cell的layoutSubviews方法
    cell.textLabel.text = appInfo.name;
    cell.detailTextLabel.text = appInfo.download;    
    //判斷有沒有圖片快取
    if (self.imageCache[appInfo.icon]) {
        NSLog(@"從快取加載圖片...");
        cell.imageView.image = self.imageCache[appInfo.icon];
        return cell;
    }    
    //設定占位圖片
    cell.imageView.image = [UIImage imageNamed:@"user_default"];    
    //判斷下載操作快取池 中是否有對應的操作
    if (self.downloadCache[appInfo.icon]) {
        NSLog(@"正在拼命下載圖片...");
        return cell;
    }
    //異步下載圖片
    //模擬網速比較慢    
    //下載操作
    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
        //        [NSThread sleepForTimeInterval:0.5];
        //模擬圖片下載速度慢
        if (indexPath.row > 9) {
            [NSThread sleepForTimeInterval:10];
        }        
        //下載圖片
        NSLog(@"下載網路圖片...");        
        NSURL *url = [NSURL URLWithString:appInfo.icon];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *img = [UIImage imageWithData:data];        
        //快取圖片
        self.imageCache[appInfo.icon] = img;        
        //主執行緒上更新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            //            cell.imageView.image = img;
            //解決圖片顯示錯行
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }];
    }];    
    //把操作添加到佇列中
    [self.queue addOperation:op];
    //把操作添加到下載操作快取池中
    self.downloadCache[appInfo.icon] = op;    
    //3 回傳cell
    return cell;
}
//接收到記憶體警告
- (void)didReceiveMemoryWarning {
    //清理記憶體
    [self.imageCache removeAllObjects];
    //
    [self.downloadCache removeAllObjects];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //點擊cell的時候,輸出當前佇列的運算元
    NSLog(@"佇列的運算元:%zd",self.queue.operationCount);
    
}
@end
@interface ViewController ()
@property (nonatomic, strong) NSArray *appInfos;
//全域佇列
@property (nonatomic, strong) NSOperationQueue *queue;
//圖片的快取池
@property (nonatomic, strong) NSMutableDictionary *imageCache;
//下載操作快取池
@property (nonatomic, strong) NSMutableDictionary *downloadCache;
@end
//1 創建模型類,獲取資料,測驗
//2 資料源方法
//3 同步下載圖片--如果網速比較慢,界面會卡頓
//4 異步下載圖片--圖片顯示不出來,點擊cell或者上下拖動圖片可以顯示
    //解決,使用占位圖片
//5 圖片快取--把網路上下載的圖片,保存到記憶體--圖片存盤在模型物件中
    //解決,圖片重復下載,把圖片快取到記憶體中,節省用戶的流量 (拿空間換取執行時間)
//6 解決圖片下載速度特別慢,出現的錯行問題,
    //當圖片下載完成之后,重新加載對應的cell
//7 當收到記憶體警告,要清理記憶體,如果圖片存盤在模型物件中,不好清理記憶體
    //圖片的快取池
//8 當有些圖片下載速度比較慢,上下不停滾動的時候,會重復下載圖片,會浪費流量
    //判斷當前是否有對應圖片的下載操作,如果沒有添加下載操作,如果有不要重復創建操作
    //下載操作的快取池
@implementation ViewController
//懶加載
- (NSArray *)appInfos {
    if (_appInfos == nil) {
        _appInfos = [HMAppInfo appInfos];
    }
    return _appInfos;
}
- (NSOperationQueue *)queue {
    if (_queue == nil) {
        _queue = [NSOperationQueue new];
    }
    return _queue;
}
- (NSMutableDictionary *)imageCache {
    if (_imageCache == nil) {
        _imageCache = [NSMutableDictionary dictionaryWithCapacity:10];
    }
    return _imageCache;
}
- (NSMutableDictionary *)downloadCache {
    if (_downloadCache == nil) {
        _downloadCache = [NSMutableDictionary dictionaryWithCapacity:10];
    }
    return _downloadCache;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //1 測驗模型資料
//    NSLog(@"%@",self.appInfos);
}
//2 資料源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.appInfos.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //1 創建可重用的cell
    static NSString *reuseId = @"appInfo";
    HMAppInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
    if (cell == nil) {
        cell = [[HMAppInfoCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseId];
    }
    //2 獲取資料,給cell內部子控制元件賦值
    HMAppInfo *appInfo = self.appInfos[indexPath.row];    
    //cell內部的子控制元件都是懶加載的
    //當回傳cell之前,會呼叫cell的layoutSubviews方法
    cell.textLabel.text = appInfo.name;
    cell.detailTextLabel.text = appInfo.download;    
    //判斷有沒有圖片快取
    if (self.imageCache[appInfo.icon]) {
        NSLog(@"從快取加載圖片...");
        cell.imageView.image = self.imageCache[appInfo.icon];
        return cell;
    }    
    //設定占位圖片
    cell.imageView.image = [UIImage imageNamed:@"user_default"];    
    //判斷下載操作快取池 中是否有對應的操作
    if (self.downloadCache[appInfo.icon]) {
        NSLog(@"正在拼命下載圖片...");
        return cell;
    }
    //異步下載圖片
    //模擬網速比較慢    
    //下載操作
    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
        //        [NSThread sleepForTimeInterval:0.5];
        //模擬圖片下載速度慢
        if (indexPath.row > 9) {
            [NSThread sleepForTimeInterval:10];
        }        
        //下載圖片
        NSLog(@"下載網路圖片...");        
        NSURL *url = [NSURL URLWithString:appInfo.icon];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *img = [UIImage imageWithData:data];        
        //快取圖片
        self.imageCache[appInfo.icon] = img;        
        //主執行緒上更新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            //            cell.imageView.image = img;
            //解決圖片顯示錯行
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }];
    }];    
    //把操作添加到佇列中
    [self.queue addOperation:op];
    //把操作添加到下載操作快取池中
    self.downloadCache[appInfo.icon] = op;    
    //3 回傳cell
    return cell;
}
//接收到記憶體警告
- (void)didReceiveMemoryWarning {
    //清理記憶體
    [self.imageCache removeAllObjects];
    [self.downloadCache removeAllObjects];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //點擊cell的時候,輸出當前佇列的運算元
    NSLog(@"佇列的運算元:%zd",self.queue.operationCount);
}
@end

注意

  • Block的回圈參考
  • 代碼重構
    • 把下載圖片的代碼提取成方法

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/207181.html

標籤:其他

上一篇:二十多歲的年紀是怎么成功四面位元組跳動,最終拿到offer的?

下一篇:Android專案:搭建一個基于MVVM的RxAndroid(RxJava)、Retrofit、OkHttp的專案

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more