内存管理的遛狗问题分析

来源:互联网 发布:selenium python 编辑:程序博客网 时间:2024/04/30 21:31

遛狗来内存处理问题


黄金法则 :有加就有减 目标就是0 只要使用 alloc retain copy 就要对应的使用 release 或者 autorelease 来释放

                        main.m文件里

#import <Foundation/Foundation.h>

#import "Person.h"

#import "Dog.h"

int main(int argc,constchar * argv[])

{

    @autoreleasepool {

Dog *dog1 = [[Dogalloc]init];

        [dog1 setID:1];

        Dog *dog2 = [[Dog alloc]init];

        [dog2 setID:2];

        Person *xiaoLi = [[Person alloc]init];

        [xiaoLi setDog:dog1];

        [xiaoLi setDog:dog2];

        [dog1 release];

        [xiaoLi release];

        [dog2 release];

        //三个alloc就是用了三个release

#if 0

       Dog *dog1 = [[Dogalloc]init];//0~1

        [dog1setID:1];

        //xiaoli要遛狗

       Person *xiaoli = [[Personalloc]init];//0~1

        [xiaolisetDog:dog1];//1~2拴上一根绳子

        //xiaowang也想遛狗

       Person *xiaowang = [[Personalloc]init];//0~1

        [xiaowangsetDog:dog1];//2~3在拴上一根绳子

        NSLog(@"dog1 retain count is %lu",[dog1retainCount]);

        //dog1 retain count is 3

        [dog1release];//3~2

        NSLog(@"dog1 retain count is %lu",[dog1retainCount]);

        //dog1 retain count is 2

        //xiaowang人死了

        [xiaowangrelease];//1~0 2~1

        NSLog(@"dog1 retain count is %lu",[dog1retainCount]);

        //person is dealloc

        //dog1 retain count is 1

         //xiaoli也死了

//        [xiaoli release];

//        NSLog(@"dog1 retain count is %lu",[dog1 retainCount]);//再次调用就是野指针了不能再次使用dog1所以如果想输出就不要采用这种方式.而使用下面的方式autorelease+自动释放池的方式

        [xiaoliautorelease];//1~0 1~0

        NSLog(@"dog1 retain count is %lu",[dog1retainCount]);

    }//跳出后计数减一不会出现野指针问题

   return0;

}

#endif

person.h文件里

#import <Foundation/Foundation.h>

#import "Dog.h"

@interface Person :NSObject

//给人添加一个实例变量 狗

{

    Dog *_dog;

}

//设置狗的外部变量

- (void)setDog:(Dog *)aDog;

- (Dog *)dog;

@end


person.m文件里

#import "Person.h"

@implementation Person

- (void)setDog:(Dog *)aDog{

    if (aDog != _dog ) {

        [ _dog release];//需要注意

        _dog = aDog;

        [aDog retain];//_dog计数器+1

    }

}

- (Dog *)dog{

    return _dog;

}

- (void)dealloc{

    NSLog(@"person is dealloc");

    [_dogrelease];//人死了就把人拥有的_dog释放

    [superdealloc];

}

@end


Dog.h文件里

#import <Foundation/Foundation.h>

@interface Dog : NSObject

{//设置狗的编号

    int _ID;

}

//设置一个外部的方法来设置狗的ID

@property(nonatomic,assign)int ID;

@end


Dog.m文件里

#import "Dog.h"

@implementation Dog

@synthesize ID = _ID;

- (void)dealloc{

    NSLog(@"dog %d is dealloc",_ID);

    [superdealloc];

}

@end






0 0
原创粉丝点击