OBJECT-C Learning Notes--memory management

Source: Internet
Author: User
Tags garbage collection goto

There are three ways to object-c memory management: Manual reference count (mrc,manual Reference count), automatic reference count (arc,automatic Reference count), automatic garbage collection.

1.MRC is the default mode of memory management. It's hard to say how easy it is to use. A little attention may result in a memory leak (what is a memory leak, a memory leak is a program that does not release memory that is no longer in use), such as alloc and releases are not used in pairs (a common phenomenon is the use of loops with break, Goto, Continue under certain conditions to jump out of the loop, and release statements in break, Goto, continue after, resulting in the failure to execute the released, resulting in memory leaks;

2.arc is strongly recommended for use after IOS5. Why, Why? Because the compiler depends on whether the incoming variable refers to a variable or a local variable, the method of returning the object is to infer where the autorelease/retain/release should be automatically added, without the programmer having to add it manually. So that programmers have more time to develop the core functions of the program.

3. automatic garbage collection is not supported by iOS (Mac support). here today is not temporarily introduced;

What is the basic idea of reference counting or what is the basic principle?

First, we create an object that executes alloc, allocating a memory space to the object. Eh, now that we have allocated space, we naturally have to release this memory space at the end of the program execution, otherwise it will cause a memory leak. How do you let the system know that it is time to release the memory space of this instance object? With the tag, then the reference count I'll take him as a "marker."

We are executing the Alloc and initialization method, the reference count will be +1 (from 0 to 1). When the system allocates memory, the "marker" is not zero. Assuming that an object a invokes object B, in order not to let B free, a needs to perform a retain operation so that B's reference counts +1, declaring that a is the owner of B. Tell the system that object B is mine and you are not free to release it. After a uses B, a sends a release message to B, declaring that B is no longer my person, and then B's reference count will be 1, if that value -1=0, then B will be released. Note: The same object can have multiple owners, and each owner must execute retain when declaring that he owns him. This ensures that the object is not released by the system until another object needs to invoke it.

If we want to know what the actual reference count is, we'll use the Retaincount method. The sample code is as follows:

#import <Foundation/NSObject.h>

#import <stdio.h>

int main () {

ID Obj=[[nsobject alloc] init];

printf (after initialization, the reference count is:%d\n, (int) [obj retaincount]);

[obj retain];

printf ("After retain is executed, the reference count is:%d\n", (int) [obj retaincount]);

[obj release];

printf ("The reference count is:%d\n" After the release is performed, (int) [obj retaincount]);

[obj release];

return 0;

}

After execution, the output results are:

After the initialization is performed, the reference count is: 1

After executing retain, the reference count is: 2

After the release is executed, the reference count is: 1

Note: alloc, init, and Release,retain must appear in pairs.


When the reference count is 0 o'clock, the system automatically calls the Dealloc method to free up memory. It is usually not allowed to call this method directly within the program.

Well, now we have a basic idea of reference counting memory management, and this basic idea is bound to expand. When we actually write a program, we encounter many objects that need to be used only once, and it can be cumbersome to release those objects one at a time. Thus, the object-c of the cocoa environment provides an automatic release mechanism . What is the mechanism? From a functional point of view, it is very simple to achieve the purpose is to use less and after the use of the object unified release. So obviously, the first thing it does is to focus these objects together, and the centralized container is--atuoreleasepool (automatic release pool). Using the same notation, use the nsautoreleasepool of the class to record. This mechanism is used in the following ways:

1. Create a NSAutoreleasePool instance object;

2. When the object needs to be released, replace release with Autorelease, mark the object (marked for later release) and put in the automatic release pool;

3. Destroy the automatic release pool, all the objects recorded in the pool are sent release messages, and then they are released uniformly.

It should be noted here that theAutorelease method does not change the reference count of an object, but it announces the abandonment of object ownership as well as release. Autorelease also want to appear with retain.

The objects that are logged to the automatic release pool are called temporary objects . This object can be created directly and will be added directly to the internal automatic release pool after it is created. such as + (ID) stringwithutf8string: (const char *) bytes,

This is the class method that generates the temporary variable (the method that does not begin with INIT to generate the object type as the beginning), and in o-c it is called the convenience constructor. All of these are manual reference counting memory management methods.


Manually manage the automatic free-release pool using the following method,

NSAutoreleasePool *pool=[[nsautoreleasepool alloc] init];

/* Carry out a series of operations *

* * no break, continue, goto statement can be used here .

[Pool release];


Automatically manage the automatic release pool, and the code becomes:

@autoreleasepool {

/* Carry out a series of operations *

/* Here you can use break, continue, goto statement * *

}


Why the latter method can use the break, continue and other statements. Because the program movement to @autoreleasepool block before the object is released, so you in the block how continue, how Goto is okay. I think that's why the arc mechanism is strongly recommended after iOS5. Using arc must be a lot less work for our programmers, but there are a few things to note when using it:

1. When using ARC memory management, you cannot add retain, release, Autorelease, and Retaincount to your program;

2. To use @autoreleasepoo instead of nsautoreleasepool;

3. Method naming must be in accordance with the naming rules, can not be arbitrarily defined with new/copy/alloc/init/mutablecopy start and ownership operations unrelated methods;

4. Do not release the instance variable in Dealloc, nor need to call [Super Dealloc];

5. Compile-time using the clang compiler, plus the compilation option-fobjc-arc;


Finally, in Xcode, we can select Edit-refactor in the menu and find a gadget called convert to Object-c arc. This tool converts code into code that supports arc. However, the code for garbage collection cannot be automatically converted.


                                 &NBS P                                   &NB Sp                                   &NB Sp                                   &NB Sp                                   &NB Sp                                   &NB Sp                                   &NB Sp                                              



Related Article

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.