ios专题 -内存管理 研究

【原创】http://www.cnblogs.com/luoguoqiang1985

  • ARC

新的规则

1. you cannot explicitly invoke dealloc, or implement or invoke retainreleaseretainCount, or autorelease

你不能显示调用 dealloc, 或者实现和调用retainreleaseretainCount, or autorelease

2.You cannot use NSAllocateObject or NSDeallocateObject

你不能使用 NSAllocateObjectNSDeallocateObject

3.you cannot use object pointers in C structures.

你不能使用C结构体指针。

4. You cannot use NSAutoreleasePool objects

你不能使用NSAutoreleasePool对象

5.you cannot use memory zones

你不能使用zones内存。

-----------------------------------------------------------------------------------------------------

语言关键字

@autoreleasepool

官方解释:

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.

自动释放池块提供了一个释放对象机制,但是避免立刻释放(正如当你从一个方法返回一个对象)。通常情况下,你不需要创建自己的自动释放池块,但也有一些情况,即要么你必须或有利于这样做。

There are, however, three occasions when you might use your own autorelease pool blocks:
If you are writing a program that is not based on a UI framework, such as a command-line tool.
If you write a loop that creates many temporary objects.
You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application.

If you spawn a secondary thread.
You must create your own autorelease pool block as soon as the thread begins executing; otherwise, your application will leak objects. (See “Autorelease Pool Blocks and Threads” for details.)

三种情况时可能会使用自己的自动释放池块:

如果你正在编写一个不基于一个UI框架,如一个命令行工具程序;

如果你编写创建许多临时对象的循环;

您可以使用一个自动释放池块内循环的下一次迭代之前,将这些对象。在循环中使用一个自动释放池块有助于减少应用程序的最大内存占用;

属性描述关键字】先罗列一下关键字吧,

retain  / strong:  strong 和 retain 类似。在新版中,strong为默认描述属性。它实现的功能相当于释放旧的对象,将旧对象的值赋予输入对象,再提高输入对象的索引计数为1 。

assgin :  简单赋值,针对值类型。如int, float....

weak   : 跟assign差不多,唯一不同是对象被销毁后自动变为nil。

copy    :  获得输入对象的一份副本,而不是输入对象的引用。使用copy的类,要实现NSCopying协议。

局部变量

__strong  它是默认的。一个对象仍然“活着”,只要有强指针指向它。

__weak    指定一个引用,但是不会保持被引用对象“活着”。弱引用被设置为nil当有对象没有强引用。

__unsafe_unretained 指定一个引用,但是不会保持被引用对象“活着”。并且当对象没有强引用,它不会设置为nil。当被引用对象销毁后,指针会是一个野指针。

__autoreleasing 它用于参数传递类型是id *,在返回的时候自动释放 

----------------------------------------

注:集合类型使用强引用去跟踪它们的内容。(the collection classes use strong references to keep track of their contents)

  • 非ARC

 retain方法 release方法
 新建对象时,使用autorelease方法

 使用NSAutoreleasePool

 注意集合引用对象时是强引用。

原文地址:https://www.cnblogs.com/luoguoqiang1985/p/3505123.html