---
title: "Day13 oc autorelease"
author: "MagicBird"
date: "2016-04-01T00:31:38Z"
tags: []
categories: ["移动开发"]
slug: "day13-oc-autorelease"
draft: false
lastmod: "2016-04-01T09:17:17Z"
id: 2287908
url: "https://magicbird.iteye.com/blog/2287908"
---

# autorelease

autorelease方法会返回对象本身，调用后会将对象放入自动释放池中，当自动释放池销毁时，会对池中所有对象做一次release操作

```
Person *p = [[[Person alloc] init] autorelease];//对象计数器并没有变
```

 ios5.0以后，自动释放池的使用

```
@autoreleasepool
{//括号开始代表创建自动释放池
}//括号结束代表销毁
```

 即

```
@autoreleasepool//延缓了对象释放的时间，缺点也是不能精确控制对象的销毁
{//1
Person *p = [[[Person alloc] init] autorelease];
//Person *p = [[[[Person alloc] init] autorelease] autorelease];调用几次autorelease，池子释放时会做几次release操作，因此会释放两次，报错
@autoreleasepool
{//2
//池子的管理采用栈数据结构（先进后出），1在栈底，2在1上面
}
}
```

 ps：占用内存较大的对象不要随便使用autorelease

ios5.0之前

```
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[pool release];
```

 代码中一般将autorelease封装到类方法中

```
@interface Person:NSObject
+(id)person;
@end


@implementation Person
+(id)person
{
return [[[self alloc] init] autorelease];//一定要使用self，可以满足子类需求，不要直接用类名
}
@end


调用时
@autorelease
{
Person *p = [Person person];
}
```

使用原则：

1、系统自带方法里没有alloc、new、copy，说明返回的对象都是autorelease的

2、开发中常提供些类方法快速创建autorelease过的对象