[笔记]MRC学习一

来源:互联网 发布:java timestamp 格式 编辑:程序博客网 时间:2024/05/21 06:28

  以前的项目都是用ARC做的,对MRC的认识仅停留在理论知识上。这次接的外包项目,我决定一定得用MRC开发了。学习网址是:http://www.raywenderlich.com/2657/memory-management-tutorial-for-ios.

  reference-counted: This means that each object keeps track of how many other objects have a pointer to it.Once the reference count goes down to zero, the memory for the object can be safely released.

// 引用计数:一个对象有多少个对象的指针保持联系,一旦这个对象的引用计数为0,这个对象的内存就会被安全释放。

/* 为什么释放后要设置对象为nil */

Note that you also set the object to nil afterwards. This is a good practice, because by setting it to nil it avoids a lot of problems. Any time you call a method on a nil object, it does nothing, but if you don’t set it to nil, if you tried calling a method on a deallocated object your program should crash.

(如果调用nil的对象,什么也不会发生,而如果调用一个已经释放的对象程序就会Crash)

/*报错*/

NSString *sushiString=[NSString stringWithFormat:@"%d %@",indexPath.row,sushiName];

[sushiString release];//释放时Crash.

(stringWithFormat方法有autorealse,so will crash)

/*autorelease*/

When you autorelease an object, it’s kind of like saying “I want you to be released at some point in the future, like the next time the run loop gets called. But for now I want to be able to use it.”

(在未来的某个时间释放....)

/*关于Autorelease的两条约定*/

1.如果方法以init或copy开始,则需要自己释放。

2.如果以其它开始,就是autorealse.

/*Retain your Wits(保持你的智慧????)*/

What if you have an object that has an autorelease pending that you want to use later on? You just need to call retain on it! That will bump the reference count up to 2, and later on when the autorelease fires it will go down to 1, and your object won’t be deallocated (since the reference count is still positive).

(如果有一个对象是autorelease在将来的某一时段,又要使用时?你只需要retain一次,引用计数就变为2。第一次autorelease释放后降为1,而你的对象则不会被释放)

When you call alloc/init, you are returned an object with a retain count of 1.


/*总结*/

  • So when you’re done with the object, you need to call release to decrement the reference count.
  • When you call a method that begins with anything except init or copy, you’re returned an object that will beautoreleased at some point in the future.
  • So if you want to use that object later, you need to call retain to increment the reference count.
  • If you create an object with alloc/init and want it to automatically be released at some point in the future for you, you can callautorelease on the object.

0 0