1. 程式人生 > >利用Runloop優化流暢度

利用Runloop優化流暢度

pbe lease ger void dom 代碼 self. pwa number

  我們可以對runloop添加觀察者,當觀察到狀態為kCFRunLoopExit,kCFRunLoopBeforeWaiting的時候,做一些耗時的處理,廢話不說,直接上代碼
  
  - (void)viewDidLoad {
  
  [super viewDidLoad];
  
  self.view.backgroundColor = [UIColor redColor];
  
  UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
  
  [self.view addSubview:tableView];
  
  tableView.delegate = self;
  
  tableView.dataSource = self;
  
  // for (int i = dasheng178.com0; i < 100000; i ++){
  
  // UIView *view = huachengj1980.com [UIView new];
  
  // [self.view addSubview:view];
  
  // }
  
  __block NSMutableArray *arr = [[NSMutableArray alloc] init];
  
  for (int i = 0; i < 10000; i ++){
  
  [arr addObject:@0];
  
  }
  
  NSLog(@"添加完了");
  
  _arr = arr;
  
  _observer = CFRunLoopObserverCreateWithHandler(CFAllocatorGetDefault(), kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
  
  NSLog(@"----監聽到RunLoop狀態發生改變---%zd", activity);
  
  if ((activity ==www.mhylpt.com kCFRunLoopExit || activity == kCFRunLoopBeforeWaiting ) && arr.count > 0){
  
  UIView *view = [UIView new];
  
  [self.view addSubview:view];
  
  [arr removeObjectAtIndex:0];
  
  NSLog(@"還有%ld",arr.count);
  
  CFRunLoopWakeUp(CFRunLoopGetCurrent(www.2636666.cn));
  
  }
  
  });
  
  CFRunLoopAddObserver(CFRunLoopGetCurrent(), _observer, kCFRunLoopDefaultMode);
  
  CFRelease(_observer);
  
  }
  
  - (NSInteger)tableView:www.taohuayuan178.com (UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  
  return 1000;
  
  }
  
  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  
  {
  
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"123"];
  
  if (!cell){
  
  cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"123"];
  
  }
  
  cell.backgroundColor = [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1.0];
  
  return cell;
  
  }
  
  - (void)dealloc www.thd178.com/{
  
  CFRunLoopRemoveObserver(CFRunLoopGetCurrent(www.douniu178.com ), _observer, kCFRunLoopCommonModes);
  
  這裏tableView滑動的時候是不會創建view的,只有滑動結束的時候才會繼續創建,這主要用在不是很著急使用的場景對流暢度進行一定的優化

利用Runloop優化流暢度