Go iOS memory management retain release

Source: Internet
Author: User

Obj-c essence is "improved C language", we all know that C language is not garbage collection (GC) mechanism (note: Although obj-c2.0 later added GC function, but not on the iphone, so for the iOS platform programmer, this is almost useless),
So when you write a program in Obj-c, the release of the resource is handled manually by the developer, which is a little bit more to worry about. Reference count this is an ancient but effective way to manage memory. Each object (specifically: an instance of the class) has a retaincount reference count, and when the object has just been created, Retaincount is 1, and the Retain method can be called manually to Retaincount+1,
You can also call the release method manually to make retainCount-1, when calling the release method, if the Retaincount value is reduced to 0, the system will automatically call the object's Dealloc method (similar to the Dispose method in C #).
Developers can release or clean up resources in Dealloc. 1, basic usage in order to demonstrate this basic way, first define a class Sample class interface part sample.h////sample.h//memorymanage_1////Created by Jimmy.yang on 11-2-19.//Copyr Ight __mycompanyname__. All rights reserved.//#import <Foundation/Foundation.h> @interface sample:nsobject {} @end Class implementation part sample.m////Sa mple.m//memorymanage_1////Created by Jimmy.yang on 11-2-19.//Copyright __mycompanyname__. All rights reserved.//#import "Sample.h" @implementation Sample-(ID) init{if (self=[super init]) {NSLog (@ "Construction The function is called! Current reference count:%d ", [self retaincount]); } return (self);} -(void) dealloc{NSLog (@ "destructor will be executed ..., current reference count:%d", [self retaincount]); [Super Dealloc];} The @end code is simple, except for "constructors" and "destructors," without any extra processing. Main program Call #import <Foundation/Foundation.h> #import "Sample.h" int main (int argc, const char * argv[]) {Sample *_sample = [sample new]; The constructor is called! Current reference count: 1 NSLog (@ "_sample.retaincount=%d", [_sample Retaincount]);//1 [_sample retain]; NSLog (@ "_sample.retaincounT=%d ", [_sample Retaincount]);//2 [_sample retain]; NSLog (@ "_sample.retaincount=%d", [_sample Retaincount]);//3 [_sample release]; NSLog (@ "_sample.retaincount=%d", [_sample Retaincount]);//2 [_sample release]; NSLog (@ "_sample.retaincount=%d", [_sample Retaincount]);//1 [_sample release];//destructor to be executed ..., current reference count: 1 NSLog (@ "_sa Mple.retaincount=%d ", [_sample Retaincount]);//1, note: Even after the destructor is executed, if you immediately reference the Retaincount of the object again,
Still returns 1, but any subsequent attempt to refer to any property or method of the object will error NSLog (@ "_sample.retaincount=%d", [_sample Retaincount]);//After the object is disposed, If you try to refer to any other method of the object, then the error//[_sample retain];//Ibid, will error return 0; This code mainly verifies whether the Retaincount is 1 at the time the object was created, and whether retain and release can change the value of Retaincount, and if Retaincount is reduced to 0 o'clock, the Dealloc function nil is automatically executed. : 1.1 If you declare only a variable of type sample (which is actually a pointer), but not instantiate, its initial value is nil1.2 variable instantiation, even if the release, Dealloc is successfully called, its retaincount does not immediately return to 0 ( can also be called immediately once and only once [xxx Retaincount]), and the pointer variable itself is not automatically classified as nil value 1.3 Dealloc is called, must be manually assigned to the value of Nil,retaincount will be automatically returned to 0 above the conclusion is the actual experiment, See the following code: Sample *s; NSLog (@ "s%@,retaincount=%d", [email protected] "is nil": @ "was not nil", [s-retaincount]);//s is nil,retaincount=0 s = [Sample new]; NSLog (@ "s%@,retaincount=%d", [email protected] "is nil": @ "was not nil", [s retaincount]);//s was not nil,retaincount= 1 [s release]; NSLog (@ "s%@,retaincount=%d", [email protected] "is nil": @ "was not nil", [s retaincount]);//s was not nil,retaincount= 1//nslog (@ "s%@,retaincount=%d", [email protected] "is nil": @ "was not nil", [s retaincount]);/error: Program received signal: "exc_bad_access". S = nil; NSLog (@ "s%@,retaincount=%d", [email protected] "is nil": @ "was not nil", [s-retaincount]);//S is nil,retaincount= 0 so do not use if (x = nil) or if ([x retaincount]==0) to determine whether the object is destroyed, unless you destroy the object each time, manually explicitly assign it to NIL2, complex case above the example is too general, only one class themselves play, if there are more than one class, And when they are connected to each other, the situation is more complicated. Below we design two classes of shoe and man (i.e. "shoes" and "people"), everyone has to wear shoes,
So man and shoe should have shoe relationship with man. Shoe.h Interface Definition Section #import <Foundation/Foundation.h> @interface shoe:nsobject {nsstring* _shoecolor; int _shoesize;} Shoe size-(void) setSize: (int) size;-(int) size; Shoe color-(void) SetColor: (nsstring*) color;-(nsstring*) color; Set the color and size of the shoe-(void) Setcolorandsize: (nsstring*) Pcolor shoesize: (int) pSize; @endShoe. M implementation part////shoe.m//memorymanage_1////Created by Jimmy.yang on 11-2-19.//Copyright __mycompanyname__. All rights reserved.//#import "Shoe.h" @implementation Shoe//constructor-(ID) init{if (self=[super init]) {_shoecolo R = @ "BLACK"; _shoesize = 35; } NSLog (@ "A pair of%@%d-yard shoes were made! ", _shoecolor,_shoesize); return (self);} -(void) SetColor: (NSString *) newcolor{_shoecolor = Newcolor;}-(nsstring*) color{return _shoecolor;}-(void) sets ize: (int) newsize{_shoesize = newSize;} -(int) size{return _shoesize;}-(void) Setcolorandsize: (NSString *) color shoesize: (int) size{[self setcolor:color]; [Self SetsIze:size];} destructor-(void) dealloc{NSLog (@ "%@" the shoes of%d yards are being destroyed by humanity! ", _shoecolor,_shoesize); [Super Dealloc];} @endMan. h defines part////man.h//memorymanage_1////Created by Jimmy.yang on 11-2-20.//Copyright __mycompanyname__. All rights reserved.//#import <Foundation/Foundation.h> #import "Shoe.h" @interface man:nsobject {nsstring *_ Name Shoe *_shoe;} -(void) SetName: (nsstring*) name;-(nsstring*) name; -(void) Wearshoe: (shoe*) Shoe; @endMan. M implementation part////man.m//memorymanage_1////Created by Jimmy.yang on 11-2-20.//Copyrig HT __mycompanyname__. All rights reserved.//#import "Man.h" @implementation Man//constructor-(ID) init{if (self=[super init]) {_name = @ "n o name "; } NSLog (@ "newcomer \"%@\ "was born! ", _name); return (self);} -(void) SetName: (NSString *) newname{_name =newname;}-(nsstring*) name{return _name;}-(void) Wearshoe: (Shoe *) Shoe {_shoe = shoe;} destructor-(void) dealloc{NSLog (@ "\"%@\ "Die! ", _name); [Super Dealloc];} @endmain function Call #Import <Foundation/Foundation.h> #import "Shoe.h" #import "Man.h" int main (int argc, const char * argv[]) { Mans *jimmy = [man new]; [Jimmy Setname:@ "Jimmy"]; Shoe *black40 =[shoe New]; [Black40 setcolorandsize:@ "Black" shoesize:40]; [Jimmy Wearshoe:black40]; [Jimmy Release]; [Black40 release]; return 0; }2011-02-23 13:05:50.550 memorymanage[253:a0f] new "No Name" was born! 2011-02-23 13:05:50.560 memorymanage[253:a0f] A pair of black 35 yards of shoes made! 2011-02-23 13:05:50.634 memorymanage[253:a0f] "Jimmy" 's Going to die! 2011-02-23 13:05:50.636 memorymanage[253:a0f] Black 40 yards of shoes are being destroyed by humanity! The above is the output, everything is normal, Jimmy and black40 occupied by the resources eventually have been released. But it's not reasonable, since shoes (black40) belong to People (Jimmy), why people die (ie: [Jimmy Release]),
But also the main function to burn off his shoes? (that is, the main function or write a single line [black40 release]) it seems that when people die, it is associated with all the things taken away, so it is more convenient. OK, let's change the Dealloc () method in man.m to the following: + View code: When the man is destroyed, the _shoe is destroyed first. So in the main () function, you no longer need to write a single line [BLACK40 release] To release black40. Now there's a new situation: Jimmy made a good friend Mike, two men became Iron buddies, then Jimmy decided to black40 his shoes, and Mike co-owned, so the main function becomes the following: + View Code trouble: When Jimmy was dead (that's the [Jimmy Release] line), he had his shoes destroyed (maybe he forgot Mike was wearing it), and Mike was going to burn his shoes black40 when he died.
But the object of the defendant was no longer there. So the program run error: Running ... 2011-02-23 13:38:53.169 memorymanage[374:a0f] new "No Name" was born! 2011-02-23 13:38:53.176 memorymanage[374:a0f] A pair of black 35 yards of shoes made! 2011-02-23 13:38:53.177 memorymanage[374:a0f] new "No Name" was born! 2011-02-23 13:38:53.179 memorymanage[374:a0f] "Jimmy" 's Going to die! 2011-02-23 13:38:53.181 memorymanage[374:a0f] Black 40 yards of shoes are being destroyed by humanity! 2011-02-23 13:38:53.183 memorymanage[374:a0f] "Mike" is dying! Program received signal: "Exc_bad_access". The red part of Sharedlibrary apply-load-rules All (GDB) indicates an error occurred: Bad_ Access means that the address does not exist. The most solution is to return to the original point, man.m Dealloc not associated with the release of shoe instances, and then put the common shoes into the main function, and so everyone hung up,
Finally, the shoe instance is destroyed, but it is estimated that the main () function will have an opinion: All two of you are dead and will trouble me for the funeral. To cite this example is to derive a principle: for new objects, the use of retain caused by the impact must be used to offset the corresponding release,
Or vice versa, either the object is not destroyed, or premature destruction causes the subsequent illegal reference to fail.

Go iOS memory management retain release

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.