4 7.OC13-内存管理4-autorelease
自动释放池(autorelease pool)
1)、自动释放池是OC里面的一种内存自动回收机制,一般可以将一些临时变量添加到自动释放池中,统一回收释放。
2)、当自动释放池销毁时,池里面的所有对象都会调用一次release方法。
autorelease
1)、OC对象只需要发送一条autorelease消息,就会把这个对象添加到最近的自动释放池中(栈顶的释放池)
2)、autorelease实际上只是把对release的调用延迟了,对于每一次autorelease,系统只是把该对象放入了当前的autorelease pool中,当该pool被释放时,该pool中的所有对象会被调用release
使用autorelease
以前
Book *book = [[Book alloc] init];
[student setBook:book];
[book release];
现在:
Book *book = [ [[Book alloc] init] autorelease];
[student setBook:book];
//不要在调用[book release];
autorelease pool疑问
1)、在iphone项目中,main()中有一个默认的Autorelease Pool,程序开始时创建,程序退时销毁,按照对Autorelease的理解,岂不是Autorelease Pool里的所有对象在程序退出时才release,这样跟内存泄露有什么区别?
2)、对于每一个Runloop,系统会隐式创建一个Autorelease pool,并且把创建好的pool放在栈顶,所有的pool会构成一个栈式结构。在每一个Runloop结束时,当前栈顶的pool会被销毁,这样这个pool里的每个对象会执行release操作。
例一:
main.m
// // main.m // OC10-内存管理2-set方法的内存管理 // // Created by qwz on 13-12-9. // Copyright (c) 2013年 renhe. All rights reserved. //
#import <Foundation/Foundation.h> #import "Student.h"
int main(int argc, const char * argv[]) { //@@autoreleasepool代表创建一个自动的释放池 @autoreleasepool { Student *stu = [[[Student alloc] init] autorelease];
Student *stu1 = [[[Student alloc] init] autorelease];
//这个str是自动释放的,不需要释放 Student *stu2 = [Student student];
//这个str是自动释放的,不需要释放 NSString *str = [NSString stringWithFormat:@"age is %i", 10]; } return 0; }
|
Student.h
// // Student.h // OC10-内存管理2-set方法的内存管理 // // Created by qwz on 13-12-9. // Copyright (c) 2013年 renhe. All rights reserved. //
#import <Foundation/Foundation.h>
@interface Student : NSObject
+ (id)student;
@end |
Student.m
// // Student.m // OC10-内存管理2-set方法的内存管理 // // Created by qwz on 13-12-9. // Copyright (c) 2013年 renhe. All rights reserved. //
#import "Student.h"
@implementation Student
- (void)dealloc{ NSLog(@"%@被销毁", self); [super dealloc]; }
+ (id)student{ Student *stu = [[[Student alloc] init] autorelease]; }
@end |