4. Cocoa memory management rules
1) when you create an object using the new, alloc, and copy methods, the reserved counter value of this object is 1. when you no longer use this object, you are responsible for sending a release or autorelease message to this object. In this way, the object will be destroyed at the end of its service life.
2) When you get an object through other methods, this assumes that the reserved counter value of this object is 1 and has been set to Auto Release, you do not need to perform any operations to ensure that the object is cleared. If you want to own this object for a period of time, you need to keep it and ensure that it is released when the operation is complete.
3) If you retain an object, You Need To (eventually) release it or automatically release it. Make sure that the retain method and the release method are used equally.
"If I use the new, alloc, or copy method to obtain an object, I must release or automatically release the object."As long as you remember this rule, you will be safe.
No matter when you have an object, there are two things that must be clarified: how to get the object? How long does it take to own the object.
For example:
NSMutableArray *array;
array = [[NSMutableArray alloc] init]; //count: 1
// use the array
[array release]; // count: 0
In the preceding example, the array is obtained using the alloc method. Therefore, you need to release the object ([array release]).
Another example:
NSMutableArray *array;
array = [NSMutableArray arrayWIthCapacity: 17];
// count: 1, autoreleased
// use the array
Arraywithcapacity in the preceding example: The method does not belong to any one of alloc, new, or copy. Therefore, we can assume that the counter value is 1 when the object is returned and has been set to Auto Release. You do not need to release the array.
5. Garbage Collection)
The Objective-C2.0 introduced an automatic memory management mechanism, also known as garbage collection. When you forget to clear created and used objects, the system automatically identifies which objects are still in use and which objects can be recycled.
Garbage collection is an optional feature. You can enable it by selecting project | edit Project Settings from the menu to enter the project information window and searching "garb ", select the required [-fobjc-GC-only] Option. As shown in:
The "-fobjc-GC" option enables code to support garbage collection and object retention and release.
After garbage collection is enabled, the general memory management commands are all empty and do not execute any operations.
Note: If you develop an iPhone, you cannot use garbage collection. In fact, when writing an iPhone program, Apple recommends that you do not use the autorelease method in your code, and avoid using convenience functions that automatically release objects.