为什么我们在ios中使用dequeue Reusable关键字

时间:2013-10-25 13:41:28

标签: ios iphone objective-c uitableview mkmapview

我想知道为什么我们使用dequeueReusableAnnotationViewWithIdentifier或dequeueReusableCellWithIdentifier?例如,defaultPinID值不合逻辑。如果我更改defaultPinID的值,则没有任何变化。在那种情况下为什么我们使用dequeueReusableAnnotationViewWithIdentifier(关键字dequeueReusable)?

在MkMapView中

 - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
    {
         MKAnnotationView *pinView = nil;
         static NSString *defaultPinID = @"ftffggf"; 
         pinView = (MKAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];  // why ? 
         .........
         ...........

         return pinView;

    }
tableView

中的

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *CellIdentifier = @"Cell";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];// why ? 

        if (cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        }
        ................
        ............... 
        return cell;

    }

2 个答案:

答案 0 :(得分:3)

这是一个资源问题,从查看应用程序没有任何改变。但是,如果单元格已经初始化,那么如果单元格已经初始化,则可以节省一些在用户上下滚动时不得不一次又一次地分配单元格的开销。

答案 1 :(得分:2)

UIView派生资源的构造和初始化相对昂贵。由于TableViews,MapViews和CollectionViews通常只需要在屏幕上一次显示一个小数字,但需要滚动浏览大量可能的对象(当用户在地图上平移或滚动集合/表视图时)Apple优化了这些类以重用已创建的数据项实例。这使得数千个行的表视图快速滚动并且流畅 - 它不必在每次滚动到视图中时创建一个全新的视图对象,然后在滚动出视图时将其销毁。我只是重用已经创建的实例并更改其上显示的数据。