This series is intended to write some of my understanding of memory management for iPhone development. It is based on the reader's understanding of the memory management of Objective C, including the Practice Principles, autorelease principle analysis, and memory leak debugging. If you do not know much about Objective C memory management, we recommend that you read the Vince Yuan tutorial first.
Memory Management is hard to understand during iPhone development. Objective-C uses a memory management mechanism between C # And C ++. C # Is a GC Based on Mark-sweep. C ++ is basically allocated and released by programmers themselves. Ojbective-C is a programmer responsible for the distribution and Release of Mark through Release, retain, alloc) counting and the system. Below are some guidelines to avoid Memory leakage and use released memory to cause program crash.
1) You must be responsible for the objects you have created. Including alloc, newObject, mutableCopy, and so on, or the object you have called retain. For these objects, you must call release or autorelease
2) You cannot release an Object returned by other functions. In principle, the called function is responsible for this. E.g. NSString str = [NSString stringWithFormat:]. You 'd better follow this rule for your own function. who applies for the function and who releases it, instead of letting the caller release it.
3) If you want to store another object in the property of an object, you must retain or copy it to avoid being release by others.
@ Propertyretain ).. The retain keyword here will automatically do this. If you declare the set Method yourself, you need to do this manually.
4) autorelease means that the object will be release by the system at a certain time.
5) Make sure that the returned object is valid. In the following example, because the heisenObject is removed from the array, a release message is sent to the heisenObject. If no one else references it, The heisenObject will be dealloc.
6) weak reference. for example, in the Document class, the Page property points to the object of the Page class, and the Parent property in the page class points to the Document, so if the retain count between each other is 1, the two objects will never be Dealloc. The solution is to change page. parent to weak reference, that is, page. parent does not retain Document. UITableView. datasource, notification observers, delegates, and outline view items are all week reference.
Original article title: Objective C Memory Management (1): Practice Principles
Link: http://www.cnblogs.com/MobileDevelop/archive/2010/07/19/1779755.html