码迷,mamicode.com
首页 > 其他好文 > 详细

OC系列高级-内存管理二

时间:2016-06-28 18:18:12      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

一.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掉包含的对象

OC系列高级-内存管理二

标签:

原文地址:http://www.cnblogs.com/kaihuacheng/p/5624274.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!