2013资料整理-iOS内存管理机制

117 篇文章 0 订阅

参考文档:http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/MemoryMgmt/Articles/MemoryMgmt.html#//apple_ref/doc/uid/10000011-SW1


Basic Memory Management Rules

The memory management model is based on object ownership. Any object may have one or more owners. As long as an object has at least one owner, it continues to exist. If an object has no owners, the runtime system destroys it automatically. To make sure it is clear when you own an object and when you do not, Cocoa sets the following policy:

  • You own any object you create

    You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, allocnewObject, or mutableCopy).

  • You can take ownership of an object using retain

    A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. You use retain in two situations: (1) In the implementation of an accessor method or an init method, to take ownership of an object you want to store as a property value; and (2) To prevent an object from being invalidated as a side-effect of some other operation (as explained in “Avoid Causing Deallocation of Objects You’re Using”).

  • When you no longer need it, you must relinquish ownership of an object you own

    You relinquish ownership of an object by sending it a release message or an autorelease message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as “releasing” an object.

  • You must not relinquish ownership of an object you do not own

    This is just corollary of the previous policy rules, stated explicitly.

  • 1.任何你创建的对象你都能获得其所有权。
       这里的创建包括使用alloc,new,copy等关键字来获得一个对象。
    2.你可以通过retain来获得一个对象的所有权。
       除了创建对象外,获得某个对象所有权的唯一方法就只有给该对象发retain消息。一旦通过retain获得了该对象的所有权,就必须遵守上面红字标注的原则:如果你拥有一个对象,那么你就有责任去释放它。
    3.如果你不再需要一个对象了,你就必须释放其所有权。
    4.你不能释放非你所有的对象所有权。

  • 所有由alloc、copy(mutablecopy)、retain、new创建的object,必须手动release(或autorelease)
  • autorelease不是自动释放,是AutoreleasePool的实例,在runloop中被”稍后“释放。

object-c提供了三种内存管理方法

1.    Retain-Release方式:简称MRR,这个需要程序员很清楚的跟踪自己的对象来管理内存,它是通过使用基类NSobject提供的引用计数模型进行管理的。当引用计数为0,此块内存被释放。

2.    自动引用字数方式:简称ARC,它也是使用了同样的引用计数机制,它在编译的时候自动帮你添加了内存管理方法。如果你使用了ARC,很多底层的机制你就无需知道了。

 3.    垃圾回收:系统自动跟踪对象的依存关系,然后自动释放不再被引用的对象。它使用一个与自动引用计数不同的机制,不过仅仅在Mac Os X中使用,不可以用于IOS。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值