The following example is encountered when studying:
#import <Foundation/Foundation.h> @interface retaintracker:nsobject @end//Retaintracker @implementation Retain
Tracker-(ID) init {if (self = [super init]) {NSLog (@ ' init:retain count of%d. ", [self retaincount]);
} return (self); }//init-(void) Dealloc {NSLog (@ "Dealloc called.
Bye Bye. ");
[Super Dealloc]; }//Dealloc @end//Retaintracker int main (int argc, const char * argv[]) {Retaintracker *tracker = [Retaintrac
Ker new]; Count:1 [tracker retain];
Count:2 NSLog (@ "%d", [tracker Retaincount]); [Tracker retain];
Count:3 NSLog (@ "%d", [tracker Retaincount]); [Tracker release];
Count:2 NSLog (@ "%d", [tracker Retaincount]); [Tracker release];
Count:1 NSLog (@ "%d", [tracker Retaincount]); [Tracker retain];
Count 2 NSLog (@ "%d", [tracker Retaincount]); [Tracker release];
Count 1 NSLog (@ "%d", [tracker Retaincount]); [Tracker release]; Count:0, dealloc it return (0);
}//Main
This is the most simple example of a reference counter, and it is also the most basic.
The knowledge points are as follows:
1. When an object calls the Alloc,new,copy method, the value of the reference counter is incremented by 1.
2. When an object calls the release method, the value of the reference counter is reduced by 1.
3. When the reference counter becomes 0, the object calls the Dealloc method itself.
4. To get the value of the reference counter, you can call the Retaincount method to get it.
5. To automatically add the value of the counter to 1, you can call the Retain method to implement.
So in the above code, the new method is used to create the object, and the counter automatically adds 1. Calling the Retain method also causes the counter to add 1. When release, the counter will be reduced by 1. When the value of the counter is 0, the Dealloc method is called. So the above code output will look like this:
2015-01-28 22:32:54.170 09.01 retaincount-1[620:23479] init:retain count of 1.
2015-01-28 22:32:54.171 09.01 retaincount-1[620:23479] 2
2015-01-28 22:32:54.171 09.01 retaincount-1[620:23479] 3< C2/>2015-01-28 22:32:54.171 09.01 retaincount-1[620:23479] 2
2015-01-28 22:32:54.171 09.01 retaincount-1[ 620:23479] 1
2015-01-28 22:32:54.171 09.01 retaincount-1[620:23479] 2
2015-01-28 22:32:54.172 09.01 retaincount-1[620:23479] 1
2015-01-28 22:32:54.172 09.01 retaincount-1[620:23479] Dealloc called. Bye Bye.
Program ended with exit code:0