zoukankan      html  css  js  c++  java
  • UITableViewCell在重用ID时为何加上Static关键字

    UITableViewCell在重用ID时为何加上Static关键字

     

    先回顾一下iOS各种变量作用域和生命周期相关知识:

    1、方法中临时变量存储在栈区,出了该方法,临时变量会被自动销毁。但是如果给方法中的临时变量前加上static,就算出了该方法,栈也不会回收该临时变量,直到程序退出才释放内存。

    2、字符串常量和所有方法之外声明的全局变量,存储在常量区,一旦生成就不会销毁,直到程序退出才释放内存。

    3、对象生成和存储在堆区,ARC下只要没有强引用,该对象的内存就会被自动回收。非ARC,当引用计数为0时,对象内存会被自动回收。

     

    //如下是创建cell时常用的代码

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

        static NSString *ID = @"hero_cell

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

        if (!cell) {

            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];

        }

    }

     

    分析:

    如果不加static修饰,直接写成 NSString *ID = @"hero_cell";

    1、字符串常量@"hero_cell",存储在常量区,一旦生成,直到程序退出才销毁;

    2、临时变量ID存在栈区,出了最后大括号}就被栈自动回收;这样每次调用cellForRowAtIndexPath方法,栈中都要重新生成临时变量ID,并让其指向常量区@“hero_cell”, 消耗内存;

    3、如果加上static,栈中的变量ID就不会销毁,一直指向常量区的@“hero_cell”,这样比较合理。

    4、图解如下:

     

     

     

    iOS开发者交流群:180080550
  • 相关阅读:
    STM32—LAN8720学习
    STM32F4以太网MAC接口
    分治思想应用题
    网易笔试编程题
    python正则表达式
    【论文笔记】CenterNet: Keypoint Triplets for Object Detection
    【论文笔记】Guided Anchor:Region Proposal by Guided Anchoring
    【论文笔记】SNIP:An Analysis of Scale Invariance in Object Detection
    【论文笔记】FCOS:Fully Convolutional One-Stage Object Detection
    【论文笔记】CenterNet:Objects as Points
  • 原文地址:https://www.cnblogs.com/stevenwuzheng/p/5377919.html
Copyright © 2011-2022 走看看