zoukankan      html  css  js  c++  java
  • 由pushViewController说起可能出线的各种死法

    做苹果开发或者果粉对导航条这个东西应该都不陌生,这咚咚在小小的屏幕上通过一个简单的View的队列管理来做到手机界面的有条理管理,但是开发过程程序员可能碰到各种死法,下面分享一二。

              例子:
    MyViewController *sampleViewController = [[[MyViewController alloc] initWithXXX] autorelease];        

    [self.navigationController pushViewController: sampleViewController animated:true];

    [sampleViewController release];

    上面代码通常在一个UITabViewController中,某一行选中后,切换到详细内容,上面代码比较简单,先从他的死法说起。

    死法1:  objectc程序员菜鸟常放的毛病导致,上面代码必死,为神马呢?

    nav的push会导致引用计数的增加,界面会苟延残喘一会,当popview的时候,最后一行release会把sampleViewController清0,接着就是autopool回收的的时候XXX了

         终结:为了避免内存泄露,alloc必对应release或者autorelease,但是必须11对应,同理

    用全局函数生成的类,你就不要release了,除非你retain(如果你要长期使用,retain是必须的),objectc的内存管理必须小心翼翼,否则。。。,我个人习惯,宁可挂掉也不能泄露,因为挂掉容易发现问题,泄露了又有几个程序员用工具分析解决呢。

    开胃菜结束,开始正题:

    MyViewController *sampleViewController = [[[MyViewController alloc]initWithXXXautorelease];        

    [self.navigationController pushViewController: sampleViewController animated:true];

    死法2:界面无反应,或者把自己界面刷了一下。

          分析可能出线的原因:

    1:self.navigationController为nil,空指针执行pushViewController直接跳过,接着sampleViewController会释放掉,所以界面会无反应。

       self.navigationController为神马会空呢?navigationController是UIViewController父类继承来的属性,不是随便都能用的,除非你当前viewController是被nav push进来的,或者用xib/代码做成navigationcontroller的root了,cocoa的代码应该是给赋值了。(题外话,我很多界面就是局部用了某个ViewController,这种情况该viewController的nav为空,如果要正确使用,可以从app取,可以自己赋值,可以整体界面取。。。想咋取都行)

    2、self.navigationController为nil,界面挂了

       如果你sampleViewController用到了网络异步请求,在initWithXXX的时候会去取数,那么你10有89会挂掉。

       原因分析:大家网络请求,经常如下:

    TwitterClient   *twitterClient = [[TwitterClient alloc] initWithTarget:self action:@selector(XXXReceive:obj:)];

    [twitterClient getXXX:param];

    恭喜你,这种情况不管是不是navigationController为空,你程序极容易挂掉,原因就是因为网络请求我们都会用异步方式来拉取数据,当数据回来之后,会回调到本类的XXXReceive:obj方法,

    但是如果界面退出了,数据才收到将如何?那就是不是空指针调用了,TwitterClient里纪录的需要回调的内存地址上神马情况都有可能是,回调。。杯具了

    解决办法:twitterClient做成成员,在析构的时候该咋收拾twitterClient的就咋收拾一下吧

    3、self.navigationController为nil,界面挂了

         和上文一样twitterClient成员了,dealloc也清理了现场,还是会挂

    原因分析:异步的问题,twitterClient已经取到数据,但是sampleViewController已经被释放了,but dealloc根本没来得及进来。。。

        解决办法,1:确保nav正确,2:尽量在界面viewDidLoad的时候网络请求数据,在dispear的时候清理网络。

    本文转载至   http://my.oschina.net/zhangzhihao/blog/108096

  • 相关阅读:
    [LeetCode] 769. Max Chunks To Make Sorted
    [LeetCode] 563. Binary Tree Tilt
    [LeetCode] 1802. Maximum Value at a Given Index in a Bounded Array
    [LeetCode] 1198. Find Smallest Common Element in All Rows
    [LeetCode] 370. Range Addition
    [LeetCode] 1749. Maximum Absolute Sum of Any Subarray
    [LeetCode] 1801. Number of Orders in the Backlog
    [LeetCode] 869. Reordered Power of 2
    [LeetCode] 841. Keys and Rooms
    [LeetCode] 1603. Design Parking System
  • 原文地址:https://www.cnblogs.com/Camier-myNiuer/p/3342206.html
Copyright © 2011-2022 走看看