OC_ Memory Management: MRC and ARC

Source: Internet
Author: User

Memory management

1.1 Memory management

1.1.1 C's memory management, and the trouble

Char *p = (char *) malloc (100*sizeof (char));

This is the dynamic memory allocation of C, we manually and the system to request 100 bytes of memory, or the system in the heap opened up 100 bytes of space, and the first address of this space is returned to the pointer variable p.

Free (p);

After the use is complete, manually release the memory space with the system, or the system reclaims the space.

As above is the simple memory management in C.

C Memory management, we manually apply, release manually. In this way, we only need to pay attention to three questions:

1, the application memory, the use of the completion of the need to release, if not released will cause a memory leak.

2, cannot be released multiple times, if released more than once, will crash.

3, can not be released early, if the early release of re-use, will also crash.

However, if the project is more complex and requires dozens of of lushu people to work together to complete, it is easy to have problems.

Let's say we open up a piece of memory that holds a piece of useful data. However, this data is not the only I use in this piece of code, and even many people, in the application of many places. The result is that even if I use this memory, I can't release him, because I'm not sure if someone else needs to use this memory elsewhere. Memory leaks are unavoidable.

Memory Management for 1.1.2 OC

Reference count (Reference count)/retention count (retain count)

For a dynamic application of memory, there is a person (pointer) to use, give this memory counter plus 1, after the use is completed, the counter will be reduced by 1, when the memory reference count is 0, we release him again, so that the above problem solved. OC, which is the use of reference counting in this way to manage memory.

1.1.3 MRC and Arc

ARC Automatic Reference Counting, automatic reference counting, by Xcode, helps us to manage memory.

MRC Manual Reference counting, manual reference counting, we manage memory manually.

The default is Arc mode after Xcode version 5.0.

1.2 MRC

1.2.1 The golden rule of memory management

For reference counting, there is a golden rule for memory management:

The basic rule to apply is everything this increases the reference counter with Alloc, [Mutable]copy[withzone:] or retain Is in charge of the corresponding [Auto]release.

All objects that start with alloc,retain,new,copy,mutablecopy or with a copy beginning with mutablecopy [create] need to be released with release or Autorelease.

Popular point of view is who pollutes who governs (who creates who releases).

1.2.2 How to change the project to MRC

XCODE5, when the project was created arc, if we want MRC, we need to make the following settings.

Select Project-target-bulid settings-automatic Reference counting change to No. (search retain or GAR)

1.2.3 Alloc and release

Create a dog class in arc mode

@interface Dog:nsobject

@end

@implementation Dog

-(void) dealloc

{

NSLog (@ "dog dealloc");

//[super Dealloc];

}

@end

Dealloc is a destructor that automatically calls this method when the object is destroyed, and we override this method here.

In the main function, write the following code:

int main (int argc, const char * argv[])

{

@autoreleasepool {

Dog *dog = [[Dog alloc] init];

}

NSLog (@ "program is about to exit");

return 0;

}

From the terminal printing information, "The program is about to exit" before the print, has already printed the dog Dealloc, that is, before the end of the program run, the dog object has been destroyed. This is arc, and Xcode manages the dog object for us.

Change Arc to MRC, then execute the program, the dog object is not destroyed, because we are now manually managed, we need to obey the golden rule of memory management, dog *dog = [[Dog alloc] init]; We need to release the dog. Change the main function code to the following form:

int main (int argc, const char * argv[])

{

@autoreleasepool {

Dog *dog = [[Dog alloc] init];

[Dog release];

}

NSLog (@ "program is about to exit");

return 0;

}

Execute the program again, as you can see from the print that the dog object has been destroyed. This is the golden rule, we alloc the dog, we need to release the dog.

Note that release does not destroy the object, so that the object's reference count is reduced by 1, and when the object's reference count is 0, the Dealloc method is automatically called to destroy the object.

1.2.4 Retain and Retaincount

Retain, the object is persisted, that is, the reference count of the object is added to 1.

Retaincount, prints a reference count for an object.

Used in the combination of the 1.2.5 class

In the code above, add the person class

@interface Person:nsobject {

A man, a dog (holding a dog)

Dog *_dog;

}

-(void) Setdog: (dog *) Dog;

-(dog *) dog;

@end

@implementation person

/* Version 1 (problematic) the person does not actually hold the dog, if in the main function [dog release], let dog's reference count minus 1, will become 0,dog destroyed.

-(void) Setdog: (dog *) Dog

{

_dog = dog;

}

  */

/* Version 2 (problematic) if a person holds another dog, it will cause the first dog to be freed and memory leaks.

-(void) Setdog: (Dog *) dog

{

_dog = [dog retain];

}

  */

/* Version 3 (problematic) if you were to have a dog and reset the dog, first release, this time, it is likely that the dog destroyed, and then, can not be retain again.

-(void) Setdog: (Dog *) dog

{

[_dog release];

_dog = [dog retain];

}

  */

Version 4 ok!, standard notation

-(void) Setdog: (Dog *) dog

{

if (_dog! = dog) {

[_dog release];

_dog = [dog retain];

  }

}

-(dog *) dog

{

return _dog;

}

-(void) dealloc

{

NSLog (@ "Person dealloc");

When the person is destroyed, the owner of the dog is destroyed.

[_dog release];

[Super Dealloc];

}

1.2.6 @property retain,assign,copy unfold

Retain expand

As in the code, the person's setter and getter method, can also be used in the property, written as follows form

@property (retain) Dog *dog;

The following will be expanded:

-(void) Setdog: (Dog *) dog

{

if (_dog! = dog)

{

[_dog release];

_dog = [dog retain];

}

}

Assign expand

Simple data type, OC memory management for simple data type int\float ...,

@property (assign) int a;,assign is directly assigned, it expands as follows:

-(void) Setdog: (int) A

{

_a = A;

}

Copy expands, copies the original object

Copy more for string

@property (copy) NSString *name;

Expand as follows:

-(void) SetName: (NSString *) name

{

if (_name! = name)

{

[_name release];

_name = [name copy];

}

}

Memory management for 1.2.7 arrays

1) When we create an array, the array will have a reference count of each object plus 1

2) When the array is destroyed, the array will have a reference count minus 1 for each object.

3) When we add an object to an array, the object is referenced and counted plus 1.

4) When we delete an object from an array, the reference count of the object is reduced by 1

In short, who pollutes who governs, manage oneself to be possible (inside the array also abides by memory management).

1.2.8 Autorelease and Autoreleasepool

In the main function, write the following code:

int main (int argc, const char * argv[])

{

@autoreleasepool {

Dog *dog = [[Dog alloc] init];

The dog was not destroyed immediately, but delayed destruction, giving the owner of the dog to Autoreleasepool

[Dog Autorelease];

This can be printed because the dog object is destroyed after the reference count of the dog is printed.

NSLog (@ "Retaincount =%lu", dog.retaincount);

}

NSLog (@ "program is about to exit");

return 0;

}

Autoreleasepool is equivalent to an array, if which object sends a AUTORELEASE message, the object's ownership is actually given to Autoreleasepool, and when Autoreleasepool is destroyed, All objects held in the Autoreleasepool send a release message.

1.2.9 Simple summary for automatic memory release:

    1. The 1 autorelease method does not alter the object's reference counter, but simply places the object in the auto-release pool;
    2. The auto-free pool is essentially the release method that calls the object when the auto-release pool is destroyed, and does not necessarily destroy the object (for example, if the reference counter of an object is >1, it cannot be destroyed at this time);
    3. Because the automatic release pool finally unified release, so if an operation compared to occupy memory (more objects or objects occupy more resources), it is best not to put in the automatic release pool;

1.3 ARC

From XCODE5, the default automatic memory management

Automatic Reference/retain counting;

1.3.1 Automatic Reference counting

The simple point is to let the compiler complete the heap space reference count plus minus, automatically released. Programmers no longer write retain release methods

Automatic memory management for "another" OC, unlike Java garbage collection. Instead, when preprocessing, add retain directly where it should be, add release where it should be released. is to add code directly.

"Another" from efficiency, ARC outperforms manual memory management.

1.3.2 MRC and Arc Mixed

1.MRC code turns into ARC code

Edit-> convert-> to Objective-c ARC

2.ARC Non-Arc mixed

In the same project, some files use arc, and some files do not use arc.

Build Phase-----> Complie Source

-fno-objc-arc (Do not use ARC for the specified file)

1.3.3 the keywords in arc mode:

__strong/__weak/__unsafe_unretain

The strong (strong reference) default property, its decorated object pointer, points to which object, retain the object, and the object to which it is being left.

Weak (weak reference) its decorated object pointer, pointing to any object is not retain. The object pointed to by such a pointer may disappear at any time. If the object disappears, the pointer will automatically become nil.

In iOS programming, proxy objects use weak references.

Unsafe_unretained The object pointer it modifies, pointing to any object that is not retain. When the pointing object disappears, the pointer does not become nil and still points to the object that has been disposed. Not recommended.

Actual work, not string, write strong, proxy object write weak, string write copy

OC_ Memory Management: MRC and ARC

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.