Sian 发表于 2014-1-12 20:48:16

第二十讲:Objective-C内存管理之AutoreleasePool

黄金法则简述版:       如果对一个对象使用了 alloc、copy、retain,那么必须使用相应的release或者autorelease。
前面已经有讲到过使用alloc、retain方法对retainCount进行内存管理,相对应地使用release进行内存释放,除此之外OC中引用较为智能的autorelease来进行内存管理,以下用一个程序进行说明:

Dog.h
//
//Dog.h
//AutoreleasePool
//
//Created by yusian on 14-1-12.
//Copyright (c) 2014年 yusian. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Dog : NSObject
{
    int _ID;
}
@property int ID;
@endDog.m
//
//Dog.m
//AutoreleasePool
//
//Created by yusian on 14-1-12.
//Copyright (c) 2014年 yusian. All rights reserved.
//

#import "Dog.h"

@implementation Dog

@synthesize ID = _ID;

- (void) dealloc{
    NSLog(@"dog is dealloc");
    ;
}

@end
main.m
//
//main.m
//AutoreleasePool
//
//Created by yusian on 14-1-12.
//Copyright (c) 2014年 yusian. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Dog.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
      
      Dog * dog = [[ init] autorelease];
      
      NSLog(@"dog retainCount1 is %ld",);
      
      ;
      
      NSLog(@"dog retainCount2 is %ld",);
      
      ;
      
      NSLog(@"dog retainCount3 is %ld",);

      
    }
   
    return 0;
}
输出结果:
2014-01-12 20:22:23.866 AutoreleasePool dog retainCount1 is 1
2014-01-12 20:22:23.868 AutoreleasePool dog retainCount2 is 2
2014-01-12 20:22:23.869 AutoreleasePool dog retainCount3 is 1
2014-01-12 20:22:23.869 AutoreleasePool dog is dealloc
Program ended with exit code: 0


Sian 发表于 2014-1-12 20:55:12

@autoreleasepool{   }括号中的对象会被自动释放,无论对象被retain多少次,无论最终对象中retainCount值为多少,括号外面都无法再次使用该对象。上述例子中,最终为1,并没有人为释放,最终dog中的dealloc方法还是被调用,说明该对象已经被释放,即autoreleasepool实现。
页: [1]
查看完整版本: 第二十讲:Objective-C内存管理之AutoreleasePool