zoukankan      html  css  js  c++  java
  • 单例初始化(MRC模式之autorelease)

    最近在一项目中,在某个地方总是有内存闪退问题,经排查之后,终于找到问题所在。

    项目中崩溃的地方使用单例写的(MRC模式),其中单例的初始化方法如下:

    + (GetCalendarEvents *)shareInstence

    {

        if (_get == nil) {

            _get = [[[GetCalendarEvents alloc] init] autorelease];

          

            _get.projectPlanArray = [[[NSMutableArray alloc] init] autorelease];

            _get.todoArray = [[[NSMutableArray alloc] init] autorelease];

            _get.noteArray = [[[NSMutableArray alloc] init] autorelease];

            _get.workLogArray = [[[NSMutableArray alloc] init] autorelease];

           _get.scheduleArray = [[[NSMutableArray alloc] init] autorelease];

           

            _get.events = [[[NSMutableDictionary alloc] init] autorelease];

                    _get.chackDictionary = [[[NSMutableDictionary alloc] init] autorelease];

           

       }

        return  _get;

    }

    上述代码中使用了autorelease,这在单例中会造成严重的内存泄露,因为单例模式下的autoRelease只有在程序退出的时候才释放,在单例模式最好不使用autoRelease,或者使用嵌套的AutoRelease release来处理。惨痛的教训。。。。可以改为如下代码而实现:

    + (GetCalendarEvents *)shareInstence

    {

        if (_get == nil) {

            _get = [[GetCalendarEvents alloc] init];

        }

        return _get;

    }

     

    - (instancetype)init

    {

        self = [super init];

        if (self) {

            _projectPlanArray = [[NSMutableArray alloc] init];

            _todoArray = [[NSMutableArray alloc] init];

            _noteArray = [[NSMutableArray alloc] init];

            _workLogArray = [[NSMutableArray alloc] init];

            _scheduleArray = [[NSMutableArray alloc] init];

            

            _events = [[NSMutableDictionary alloc] init];

            

            _chackDictionary = [[NSMutableDictionary alloc] init];

            

        }

        return self;

    }

    本人也没怎么用过手动内存管理,只是公司的项目比较早。。。哎,好苦逼。。。。在此总结一下!!!!!

  • 相关阅读:
    vmware里面的名词 vSphere、vCenter Server、ESXI、vSphere Client
    SQL Server2014 SP2新增的数据库克隆功能
    看完SQL Server 2014 Q/A答疑集锦:想不升级都难!
    Windows Server 2012 NIC Teaming 网卡绑定介绍及注意事项
    最近帮客户实施的基于SQL Server AlwaysOn跨机房切换项目
    基于本地存储的kvm虚拟机在线迁移
    SQL Server 数据加密功能解析
    android开发之GestureDetector手势识别(调节音量、亮度、快进和后退)
    Datazen介绍
    jquery智能弹出层,自己主动推断位置
  • 原文地址:https://www.cnblogs.com/pangbin/p/5177031.html
Copyright © 2011-2022 走看看