iOS~AutoRelease 理解

2019-01-03  本文已影响1人  派大星的博客

AutoRelease相关链接的读后感:通过调用[obj autorelease]来延迟obj内存的释放,但是通过嵌套的Autorelease Pool来提前大量局部变量的内存的释放。


1、常见的问题

//  NSObject 声明文件
@protocol NSObject
- (instancetype)retain OBJC_ARC_UNAVAILABLE;
- (oneway void)release OBJC_ARC_UNAVAILABLE;
- (instancetype)autorelease OBJC_ARC_UNAVAILABLE;
- (NSUInteger)retainCount OBJC_ARC_UNAVAILABLE;
@end

2、[obj autorelease] 的方法调用 和 Autorelease Pool Blocks 的 区别和联系?

这两者本来是没什么可以混淆的地方,但是提到"自动释放池"的时候,下意识的就会搞混,切记区分"方法调用"和"Block"。

首先,在MRC中,调用[obj autorelease]来延迟内存的释放是一件简单自然的事, 对象调用 [obj autorelease] 才会入池。

而"自动释放池块"提供了一种机制,在这种机制中,您可以放弃对象的所有权,但避免立即释放它(例如当您从方法返回对象时)。通常,您不需要创建自己的自动释放池块,但是在某些情况下,您必须这样做,或者这样做是有益的。

Autorelease pool blocks provide a mechanism whereby you can relinquish ownership of an object, but avoid the possibility of it being deallocated immediately (such as when you return an object from a method). Typically, you don’t need to create your own autorelease pool blocks, but there are some situations in which either you must or it is beneficial to do so.


3、@autoreleasepool{}的原理

AutoreleasePoolPage

void *context =  objc_autoreleasePoolPush();
// {}中的代码
objc_autoreleasePoolPop(context);

嵌套的AutoreleasePool:嵌套的栈

timg-2.jpeg timg.jpeg

4、Ownership Policy Is Implemented Using Retain Counts

The ownership policy is implemented through reference counting—typically called “retain count” after the [retain] method. Each object has a retain count.


5、 autorelease

Adds the receiver to the current autorelease pool and returns self. You add an object to an autorelease pool so that it will receive a release message-and thus might be deallocated-when the pool is destroyed.


6、three occasions when you might use your own autorelease pool blocks:

(See Autorelease Pool Blocks and Threads for details.)

译: 什么时候用 AutoreleasePool

7、什么对象会自动加入 autoreleasepool :

上一篇 下一篇

猜你喜欢

热点阅读