内存管理之自动释放池

来源:互联网 发布:淘宝直播人数真的吗 编辑:程序博客网 时间:2024/04/28 16:27

Main.m

#import "Dog.h"int main(int argc, const char * argv[]){    /*________________________自动释放池的使用__________________________*/   /*    //方式一:    //创建dog对象    Dog *dog = [[Dog alloc] init];  //1        //创建自动释放池对象    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];        //将dog放入到池子中,注意:此时的dog的引用计数不变,还是1,等到池子释放的时候才会释放    [dog autorelease];  //1        NSLog(@"dog 还没有被释放");        //自动释放池释放,此时他会将池子中的每一个对象发送一条release消息    [pool release];        //drain 会将池子中的每一个对象发送一条release消息,但是池子没有销毁//    [pool drain];            //方式二:    @autoreleasepool {  //等价于:NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];        //作用域                Dog *dog1 = [[Dog alloc] init];                [dog1 autorelease];                    }   //等价于: [pool release];    */        /*________________________自动释放池的嵌套__________________________*/    NSAutoreleasePool *pool1 = [[NSAutoreleasePool alloc] init];        Dog *dog1 = [[Dog alloc] init];    dog1.name = @"大黄";  //大黄放入pool1        [dog1 autorelease]; //放入自动释放池        NSAutoreleasePool *pool2 = [[NSAutoreleasePool alloc] init];            //创建dog2    Dog *dog2 = [[Dog alloc] init];        dog2.name = @"小黑";  //小黑放到pool2    [dog2 autorelease]; //放入自动释放池        [pool2 release];        [pool1 release];        return 0;}

Dog.h

@interface Dog : NSObject@property(nonatomic, copy) NSString *name;

Dog.m

- (void)dealloc{    NSLog(@"%@  dog dealloc",_name);        [_name release];        [super dealloc];}


0 0