OBJECTIVE--C Memory Management Basics

Source: Internet
Author: User

2016-08-01 15:36:30

    1. Memory Management in OC:
    • Objective--c added garbage collection mechanism, as a beginner, need to clear memory management, when to apply for memory, when to release memory, develop good programming habits, develop a memory leak-free application. For your own development of the application, manage the memory itself, when the program needs space, then manually allocate space, when the space or other resources are no longer needed, manual recycling.
    • The Alloc+init in OC is the opening space, and the release in OC is an indication of the free space.

2. Automatic release of the pool

    • The auto-free pool is an automatic memory recovery mechanism for OC, which can be released by a unified collection of temporary variables through the automatic release pool.
    • Whenever an object receives an Autorelease message, the object is placed in the auto-free pool, and when the auto-free pool is freed, the object in the auto-free pool receives the release message once.
    • When an object receives a autorelease message, the object is placed in the nearest auto-release pool, and you can send an release message to the auto-release pool when the auto-free pool needs to be emptied.

1 nsautoreleasepool *pool = [[NSAutoreleasePool alloc] init]; 2 [pool addobject:tt]; 3 [pool addobject:ttt]; 4 [pool addobject:c]; 5 [pool drain];

    • Typically, a command-line tool application in a cocoa contains the code in the main function:
int Main () {      @autoreleasepool    {          NSLog (@ "hello,world");      }          return 0 ;  }
    • In short, the MRC, when sending an autorelease message to an object, is not released immediately, but is later released, of course, not at any time later.

  #import  <foundation/foundation.h> @interface   xypoint:nsobject{ int      X;  int   Y; @property (nonatomic)  int   x, y;  -(id ) Initwithx: (int ) _x AndY: (int  ) _y;   @end  
#import " XYPoint.h " @implementation Xypoint @synthesize x, y; -(ID) INITWITHX: (int) _x AndY: (int) _y{    if (self = [ Super Init])    {        = _x;         = _y;    }     return Self ;} @end
#import<Foundation/Foundation.h>#import "XYPoint.h"intMainintargcConst Char*argv[]) {@autoreleasepool {xypoint*P1 = [[Xypoint alloc] Initwithx:1AndY:1]; NSLog (@"%d,%d", p1.x, P1.Y);                [P1 autorelease]; Sleep (Ten); p1.x=Ten; P1.y=Ten; NSLog (@"%d,%d", p1.x, P1.Y); }    return 0;}

    • If the autorelease message is sent to the P1, all results are output normally and P1 will not be released immediately. Instead, the P1 is destroyed when the automatic release pool is released.
    • The use of autorelease requires attention:
    • Sending too many autorelease messages first, just as you send too much release, can cause a memory failure when emptying the auto-free pool.
    • Second, although the release message can be replaced with autorelease, but for system performance considerations, you can use the release where possible without using autorelease, because the auto-free pool does more work than the direct use of release.
    • Finally, the automatic release of the pool's "delayed release mechanism" may result in useless memory consumption.
    • When you create an object, you do not need to use release or autorelease if you are not using Alloc. But if you display the use of alloc, then you should not forget to use release or Autorelease.
    • When the auto-free pool is released, objects in the auto-free pool may be freed. This is because when the auto-release pool is released, a release message is sent to each object in the release pool, which causes the value of the object's reference counter to be reduced by 1, and if the value of the object reference counter is reduced to 0, the system sends an DEALLOC message to the object to completely destroy the object.

3. Reference counters

    • When the root class NSObject or its derived classes involving OC are involved, we often use the Alloc method to request memory and reclaim the memory by sending release messages to the object. But things aren't always that simple. An application that is running may reference the object you create in multiple places, such as an object that can be stored in an array or referenced elsewhere by an instance variable. In this case, the object is no longer used unless you are sure that every consumer who references the object. Otherwise, you may not be able to release the memory of the object, if the hasty recovery of space may also create a memory leak or two delete problems. At this point, we need to manage the memory.
    • Memory management in OC is also an important part of the content, in C, the memory request is released once, although multiple pointers can point to the same space, but released only through the pump a pointer to reclaim the space. However, in OC, the reference counter mechanism is added to record the number of references to this object, and the object is referenced several times, and it needs to be released several times.
    • Typically, a new object is created, the value of the object reference counter is set to 1, and if the object is referenced in other code, you can send an retain message to the object, retain can add 1 to the value of the object's reference counter, and if this object is not needed in this code, You can send an ralease message to an object, which is the value of the object reference counter minus 1.
    • There are also additions and deletions to the foundation framework that are worth manipulating, for example, adding objects to an array or moving arrays can have an effect on the object's reference counter.
    • AClass *anobject = [[AClass alloc] init];//reference count = 1 after alloc
    • [AnObject retain]; Reference count + = 1 after retain//2
    • [AnObject retain];//reference count-= 1 after retain//1
    • [AnObject retain];//reference Count = = 0 Then dealloc//0

In fact, there are three ways to increase or decrease the value of the object reference counter. This also means that when you release an object, you should be aware of several limitations:

    • Show creating an object using Alloc
    • Show using Copy[withzone:] or Mutablecopy[withzone:] Copy Object
    • Show using retain

Use the previous Xypoint class to test:

1 #import<Foundation/Foundation.h>2 #import "XYPoint.h"3 intMainintargcConst Char*argv[])4 {5 @autoreleasepool6     {7Xypoint *P1 = [[Xypoint alloc] Initwithx:1AndY:1];//with Alloc, the value of the object reference count is increased from 0 to 18NSLog (@"%d,%d", p1.x, p1.y);9NSLog (@"%ld", [P1 retaincount]);//1Ten[P1 retain];//add 1 to the value of the object reference counter using retain OneNSLog (@"%ld", [P1 retaincount]);//2 A          - [P1 release]; - [P1 release]; the         -     } -     return 0; -}
    • An object can receive any retain or release message, as long as you can guarantee that the value of the object's reference counter is greater than 0. Once the value of the object reference counter is reduced to 0, the compiler sends an DEALLOC message to the object to completely destroy the object (that is, the Dealloc method is automatically executed). If the release message continues to be sent to the object at this point, a memory error can cause the program to crash.
    • We can get the value of the object reference counter by sending an Retaincount message to the object. This method is rarely used, mainly to help us better understand how the reference counter changes when an object Alloc,retain and release.

4. Memory allocation, initialization

(1) in OC, allocation space and initialization are two different methods. The allocation of space is handled through the class method Alloc, where one initializes all instance variables, but the instance variable except for the pointer inherited from NSObject ISA (IS-A) is set to 0 (at run time, the value of ISA can identify the type of the newly created object)

(2) However, for instance variables, their initial values should depend on the parameters in the constructor, and in obj, the associated initialization code is placed in a method whose names usually begin with Init.

(3) in OC, the creation of objects is strictly divided into two steps, space allocation and initialization.

    • The ALLOC message is sent to the class object, and the INIT message is sent to the new object Alloc. and is not selectable at initialization time. You must follow init after alloc.
    • In OC, initialization is also implemented using methods, and initialization methods typically start with init instead of forcing Init, but it is strongly recommended that the initialization method be named with the following rule: The method name of the initialization method must begin with Init.

(4) The following are constraints or specifications for the correct implementation of the initialization method:

    • First name starts with Init
    • Method needs to return an object for later use.
    • Method body, executes the initialization method of the parent class.
    • Method body to check the return value of the parent class Init method.
    • Methods in the body to properly handle the initialization of errors, whether this class or inherited, should be taken into account.

(5) There are two special identifiers for a message self and super, self refers to the current object, and Super refers to the parent class. In OC, the This keyword is not in place and is replaced by self. In fact, self is not the real keyword, and each method will have a hidden parameter, self, whose value is the current object.

(6) Under MRC, the program (alloc, copy, retain) must appear in pairs with the release.

(7) Handle errors in the initialization method.

(8) When initializing an object with an initialization method, there are three potential hazards that can cause a program error.

    • The parameters of the method. Before executing [super INIT], the initialization must stop if the parameters of the method are invalid.
    • Executes the Init method of the parent class. When executing the Init method of the parent class, it is possible that the initialization is unsuccessful, at which point we should discard the current initialization operation.
    • Initializes the instance variables that are unique to the class. Initializes the parent class, finishes initializing the inherited member from the parent class, and then initializes the unique member, but once the resource allocation fails, the initialized method needs to be terminated.

5. Memory Recovery

    1. in OC, the instance method Dealloc is used to dispose of the heap space that the instance variable in the object points to. When the Dealloc method is called by the
    2. OC, the Dealloc method is automatically executed to destroy the object when the object's reference counter has a value of 0 o'clock.
    3. to learn a better way to release the space occupied by the instance variable origin in the example above, and the space occupied by origin is released in the main function through [[C Origin] release]. Setorigin: The origin reference counter value is reduced by one in the method, so we need to override the Dealloc method in the Circle class.
    4. When overriding the Dealloc method, you must ensure that not only the space occupied by your instance variables is freed, but also the space occupied by the inherited variables, so you can do this by sending Dealloc to super. An example of an implementation of the
    5. dealloc function
1 -(void) dealloc2{3     // call set function, first release, Empty again.  4     self.origin = nil;  // reference count value minus 1 5     // to release an instance variable inherited from the parent class 6 }

OBJECTIVE--C Memory Management Basics

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.