runloop優(yōu)化tableView的實現(xiàn)

runloop如何優(yōu)化tableView

回答:
把任務以block塊的方式封裝起來,存放到任務數(shù)組中,若任務數(shù)組中的任務數(shù)超出最大任務數(shù),則刪除靠前的任務,注冊runloop的觀察者,在回調方法里,執(zhí)行任務數(shù)組中的一個任務,并刪除執(zhí)行后的任務。添加timer事件,防止runloop進入休眠狀態(tài)。

回答解析:
為了解決tableView的卡頓現(xiàn)象,可以runloop一次處理一個任務,

根據(jù)當前的runloop和觀察者的上下文,通過CFRunLoopObserverCreate函數(shù),定義一個觀察runloop即將進入休眠狀態(tài)(BeforeWaiting)時的觀察者,添加runloopcommon模式下的監(jiān)聽,

在觀察者回調函數(shù)中,根據(jù)觀察者上下文執(zhí)行當前對象任務數(shù)組中的第一個任務,任務執(zhí)行后從數(shù)組中移除,

在繪制cell的方法(即cellForRow)中,調用添加任務的方法,在這個方法的內(nèi)部,將用block代碼塊包裝的任務添加到數(shù)組中,若超出最大任務數(shù),則刪除之前的任務,便于觀察者回調函數(shù)分開執(zhí)行任務,減少對系統(tǒng)資源的消耗,

最后添加timer或source0 事件,使runloop不進入休眠狀態(tài)。

卡頓原因:

tableView加載過多的高清大圖,拖動tableView時,runloop不僅需要處理拖動事件,還要處理圖片渲染,從而造成卡頓。

需求:
從網(wǎng)絡加載高清大圖到UITableViewCell上,而且每個Cell上面加載多張圖片,當cell數(shù)量過多的時候,我們需要保持流暢度和加載速度。

通過runloop優(yōu)化TableView

整體來講:在cellforRow方法里,以block代碼塊的方式把任務存儲到數(shù)組中,注冊runloop的觀察者,完成回調方法,執(zhí)行block任務,從數(shù)組中刪除執(zhí)行后的任務,保持runloop不休眠。
步驟:

1、獲取當前主線程的 runloop
  //獲取當前RunLoop
//swift實現(xiàn)
  let runLoop: CFRunLoop = CFRunLoopGetCurrent()
  //獲取當前RunLoop
// oc實現(xiàn)
 CFRunLoopRef runloop = CFRunLoopGetCurrent();
2、創(chuàng)建觀察者 CFRunLoopObserverRef , 來監(jiān)聽 runloop
  • 創(chuàng)建觀察者用到的核心函數(shù)就是
    CFRunLoopObserverCreate:
// allocator:該參數(shù)為對象內(nèi)存分配器,一般使用默認的分配器kCFAllocatorDefault。
// activities:要監(jiān)聽runloop的狀態(tài)
/*
typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) {
        kCFRunLoopEntry         = (1UL << 0), // 即將進入Loop
        kCFRunLoopBeforeTimers  = (1UL << 1), // 即將處理 Timer
        kCFRunLoopBeforeSources = (1UL << 2), // 即將處理 Source
        kCFRunLoopBeforeWaiting = (1UL << 5), // 即將進入休眠
        kCFRunLoopAfterWaiting  = (1UL << 6), // 剛從休眠中喚醒
        kCFRunLoopExit          = (1UL << 7), // 即將退出Loop
        kCFRunLoopAllActivities = 0x0FFFFFFFU // 所有事件
    };
*/
// repeats:是否重復監(jiān)聽
//   order:觀察者優(yōu)先級,當Run Loop中有多個觀察者監(jiān)聽同一個運行狀態(tài)時,根據(jù)該優(yōu)先級判斷,0為最高優(yōu)先級別。
// callout:觀察者的回調函數(shù),在Core Foundation框架中用CFRunLoopObserverCallBack重定義了回調函數(shù)的閉包。
// context:觀察者的上下文。
CF_EXPORT CFRunLoopObserverRef CFRunLoopObserverCreate(CFAllocatorRef allocator,
                                                       CFOptionFlags activities,
                                                       Boolean repeats,
                                                       CFIndex order,
                                                       CFRunLoopObserverCallBack callout,
                                                       CFRunLoopObserverContext *context);
2-1、創(chuàng)建觀察者
// 1.定義上下文
    //runloop觀察者上下文, 為下面創(chuàng)建觀察者準備,只有創(chuàng)建上下文才能在回調了拿到self對象,才能進行我們的邏輯操作. 這是一個結構體。

    /**

     typedef struct {

     CFIndex version;

     void * info;

     const void *(*retain)(const void *info);

     void (*release)(const void *info);

     CFStringRef (*copyDescription)(const void *info);

     } CFRunLoopObserverContext;

     **/
CFRunLoopObserverContext context = {
    0,
    (__bridge void *)(self),
    &CFRetain,
    &CFRelease,
    NULL
};
// 2.定義觀察者
static CFRunLoopObserverRef defaultModeObserver;
// 3.創(chuàng)建觀察者
defaultModeObserver = CFRunLoopObserverCreate(kCFAllocatorDefault,
                                              kCFRunLoopBeforeWaiting,
                                              YES,
                                              0,
                                              &callBack,
                                              &context);
// 4.給當前runloop添加觀察者
// kCFRunLoopDefaultMode: App的默認 Mode,通常主線程是在這個 Mode 下運行的。
// UITrackingRunLoopMode: 界面跟蹤 Mode,用于 ScrollView 追蹤觸摸滑動,保證界面滑動時不受其他 Mode 影響。
// UIInitializationRunLoopMode: 在剛啟動 App 時進入的第一個 Mode,啟動完成后就不再使用。
// GSEventReceiveRunLoopMode: 接受系統(tǒng)事件的內(nèi)部 Mode,通常用不到。
// kCFRunLoopCommonModes: 這是一個占位的 Mode,沒有實際作用。
CFRunLoopAddObserver(runloop, defaultModeObserver, kCFRunLoopCommonModes);
// 5.內(nèi)存管理
CFRelease(defaultModeObserver);
   ///添加runloop的監(jiān)聽
    fileprivate func addRunloopObserver() {
        //獲取當前RunLoop
        let runLoop: CFRunLoop = CFRunLoopGetCurrent()
        //定義一個上下文
        var context: CFRunLoopObserverContext = CFRunLoopObserverContext(version: 0, info: unsafeBitCast(self, to: UnsafeMutableRawPointer.self), retain: nil, release: nil, copyDescription: nil)
        //定義一個觀察者
        if   let observer = CFRunLoopObserverCreate(kCFAllocatorDefault, CFRunLoopActivity.beforeWaiting.rawValue, true, 0, self.observerCallbackFunc(), &context){
            //添加當前RunLoop的觀察者
            CFRunLoopAddObserver(runLoop, observer, .commonModes);
        }
    }
2-2、實現(xiàn) callBack 函數(shù),只要檢測到對應的runloop狀態(tài),該函數(shù)就會得到響應。
//回調函數(shù)
static void callBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
    
    ViewController *vc = (__bridge ViewController *)info;
    
    //無任務  退出
    if (vc.tasksArr.count == 0) return;
    
    //從數(shù)組中取出任務
    runloopBlock block = [vc.tasksArr firstObject];
    
    //執(zhí)行任務
    if (block) {
        block();
    }
    
    //執(zhí)行完任務之后移除任務
    [vc.tasksArr removeObjectAtIndex:0];
    
}
///回調函數(shù)
    func observerCallbackFunc() -> CFRunLoopObserverCallBack {
        return {(observer, activity, context) -> Void in
            if context == nil {//如果沒有取到  直接返回
                return
            }
            // 崩潰的與原因不在這里  isFromADGuide 的問題 不應該取反
            //取出上下文 就是當前的vc
            let vc = unsafeBitCast(context, to: XXXFinancialFroductListVC.self)
            //取出任務
            if let unit = vc.tasksArr.first, let indexP = vc.tasksIndexPathArr.first {
                var result = false
                while (result == false && !vc.tasksArr.isEmpty && !vc.tasksIndexPathArr.isEmpty){
                    //執(zhí)行任務
                    result = unit(indexP);
                    //干掉第一個任務
                    _ = vc.tasksArr.remove(at: 0)
                    _ = vc.tasksIndexPathArr.remove(at: 0)
                }
            }
        }
2-3、從上面的函數(shù)實現(xiàn)中我們看到了block、arr等對象,下面解析下
//使用 Array 來存儲需要執(zhí)行的任務
- (NSMutableArray *)tasksArr {
    if (!_tasksArr) {
        _tasksArr = [NSMutableArray array];
    }
    return _tasksArr;
}
// maxTaskCount 來表示最大任務數(shù),優(yōu)化項目
@property (nonatomic, assign) NSUInteger maxTaskCount;
...
// 當超出最大任務數(shù)時,以前的老任務將從數(shù)組中移除
self.maxTaskCount = 50;
///任務數(shù)組
var tasksArr: [RunloopBlock] = []
///任務對應indexPath數(shù)組
var tasksIndexPathArr: [IndexPath] = []
 ///最大任務 10
let maxQueueLength = 10

使用 block代碼塊 來包裝一個個將要執(zhí)行的任務,便于 callBack 函數(shù)中分開執(zhí)行任務,減少同時執(zhí)行對系統(tǒng)資源的消耗。

//1. 定義一個任務block
typedef void(^runloopBlock)();
//2. 定義一個添加任務的方法,將任務裝在數(shù)組中
- (void)addTasks:(runloopBlock)task {
    //保存新任務
    [self.tasksArr addObject:task];
    //如果超出最大任務數(shù) 丟棄之前的任務
    if (self.tasksArr.count > _maxTaskCount) {
        [self.tasksArr removeObjectAtIndex:0];
    }
}
//3. 將任務添加到代碼塊中
// 耗時操作放在任務中
[self addTasks:^{
    UIImageView *img1 = [[UIImageView alloc] initWithFrame:CGRectMake(kBorder_W,
                                                                      kBorder_W,
                                                                      width,
                                                                      kCell_H-kBorder_W)];
    img1.image = [UIImage imageNamed:@"Blue Pond.jpg"];
    [cell addSubview:img1];
}];

///定義blcok
typealias RunloopBlock = ((IndexPath) -> Bool)
private let cellID = "XXXFinancialFroductListVCCell"

   override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: XXXFinancialProductCell = tableView.dequeueReusableCell(withIdentifier: cellID) as! XXXFinancialProductCell
        self.addTask(indexPath) { (indexP) -> Bool in
            cell.kaDunHandler(self.pageManager.dataArr, tableView, indexP)
            return true
        }
        return cell
    }

   ///添加新的任務的方法!
    func addTask(_ indexP: IndexPath, unit: @escaping RunloopBlock) {
        self.tasksArr.append(unit)
        self.tasksIndexPathArr.append(indexP)
        //判斷一下 保證沒有來得及顯示的cell不會繪制
        if self.tasksArr.count > self.maxQueueLength {
            _ = self.tasksArr.remove(at: 0)
            _ = self.tasksIndexPathArr.remove(at: 0)
        }
    }

4、使 runloop 不進入休眠狀態(tài)。

runloop 在加載完 cell 時沒有其他事情做了,為了節(jié)省資源消耗,就進入了休眠狀態(tài),等待有任務時再次被喚醒。在我們觀察者的 callBack 函數(shù)中任務被一個個取出執(zhí)行,還沒有執(zhí)行完,runloop 就切換狀態(tài)了(休眠了), callBack 函數(shù)不再響應。導致出現(xiàn)上面的情況。

解決方法:

//創(chuàng)建定時器 (保證runloop回調函數(shù)一直在執(zhí)行)
CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self
                                                         selector:@selector(notDoSomething)];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];

- (void)notDoSomething {
    // 不做事情,就是為了讓 callBack() 函數(shù)一直相應
}
//定時器,保證runloop一直處于循環(huán)中
@property (nonatomic, weak) NSTimer *timer;

//給runloop一個事件源,讓Runloop不斷的運行執(zhí)行代碼塊任務
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(setRunLoop) userInfo:nil repeats:YES];

//此方法主要是利用計時器事件保持runloop處于循環(huán)中,什么都不干,APP性能影響并不大。但cpu增加負擔
-(void)setRunLoop{}
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容