zoukankan      html  css  js  c++  java
  • viewDidUnload释疑

    以前对于为什么在viewDidUnload将property设为nil就可以将内存释放防止内存泄漏感到疑惑.今天看文档的时候终于想明白了.

    首先我们来看一个例子:

    1 @interface Counter : NSObject 
    2 {
    3 NSNumber *_count;
    4 }
    5 @property (nonatomic, retain) NSNumber *count;
    6 @end;

    count property的access method 相当于下面两个methods:

     1 - (NSNumber *)count
    2 {
    3 return _count;
    4 }
    5
    6 - (void)setCount:(NSNumber *)newCount
    7 {
    8 [newCount retain];
    9 [_count release];
    10 // Make the new assignment.
    11 _count = newCount;
    12 }
    -(void)viewDidUnload
    {
    self.count = nil;
    }

    我们可以将self.count = nil这句带入setCount去执行.变成

    1 - (void)setCount:(NSNumber *)newCount
    2 {
    3 [nil retain];
    4 [_count release];
    5 // Make the new assignment.
    6 _count = nil;
    7 }

    在OBJC中向nil发消息是允许的,接着_count拥有的内存被释放,并且指向了nil,防止指针悬空,一切那么简洁自然.这也是设置property的一个好处吧,方便




  • 相关阅读:
    Oracle基础知识
    tomcat服务器
    jquery实现常用UI布局
    css画布
    css布局
    jquery快速常用技能
    css快速浏览
    css选择器
    spring boot项目mybatis配置注解+配置文件
    sass的安装和基础语法
  • 原文地址:https://www.cnblogs.com/woainilsr/p/2368841.html
Copyright © 2011-2022 走看看