• OC系列高级-内存管理二


    一.MRC模式下set和get方法

    首先我们创建一个Dog类

    Dog.h:

    #import <Foundation/Foundation.h>
    
    @interface Dog : NSObject
    @property (assign) int ID;
    @end
    

    Dog.m:

    #import "Dog.h"
    
    @implementation Dog
    @synthesize ID = _ID;
    - (void)dealloc{
        NSLog(@"Dog ID%d is death",_ID);
        [super dealloc];
    }
    
    @end
    

    再创建一个Person类

    Person.h:

    #import <Foundation/Foundation.h>
    #import "Dog.h"
    @interface Person : NSObject
    {
        Dog *_dog;
    }
    -(void)setDog:(Dog *)newDog;
    -(Dog *)dog;
    @end
    

    Person.m:

    #import "Person.h"
    
    @implementation Person
    
    -(void)setDog:(Dog *)newDog{
        NSLog(@"%d",_dog.retainCount);
        if(_dog != newDog){
            [_dog release];
            _dog = nil;
            NSLog(@"%d",_dog.retainCount);
            _dog = [newDog retain];
            NSLog(@"%d",_dog.retainCount);
        }
    }
    
    -(Dog *)dog{
        return [_dog autorelease];
    }
    
    - (void)dealloc
    {
        NSLog(@"Person is death");
        [super dealloc];
    }
    
    @end
    

    在main函数中我们创建两个dog,并且创建person

            Dog *dog1 = [[Dog alloc]init];
            dog1.ID = 1;
            Dog *dog2 = [[Dog alloc]init];
            dog2.ID = 2;
            
            Person *p = [[Person alloc]init];
    

    person set一个dog

       [p setDog:dog1];
    

    此时,set方法完之后dog.retainCount值为2,因为dog创建和retain

    当我们把dog1 release操作

            [dog1 release];
            NSLog(@"%d",dog1.retainCount);  //值为1
    
    NSLog(@"%zd",p.retainCount);  //person的retainCount值为1,因为只是创建
    

    我们把person release操作

            [p release];
            p = nil;
    

    此时person retainCount值为0,并且调用了dealloc方法,但是person里的dog的retainCount值为1;所以我们在回收person时要把它的对象属性release操作,要不会引起内存空间的泄漏

    当person没有执行release操作,再set一个dog1操作,此时,person的dog的retainCount值为1,即没有进行retain操作

    注意点:

    1.析构函数的release时一定要release掉包含的对象

    未来的你会感谢今天努力的自己 ------Alen
  • 相关阅读:
    .NETCore 之 中间件 02
    .NETCore 之 中间件 01
    .NetCore 之AOP扩展ExceptionFilter
    Unity ICO
    CentOS7离线安装Mysql8.0
    CentOS7离线安装devtoolset-9并编译redis6.0.5
    Centos7离线安装gcc4.8
    C#进行图片压缩(对jpg压缩效果最好)
    实现ASP.Net Core3.1运行在DockeDesktop下并用Nginx实现负载均衡
    WPF实现TextBlock呼吸灯效果
  • 原文地址:https://www.cnblogs.com/kaihuacheng/p/5624274.html
Copyright © 2020-2023  润新知