iOS Development-memory management

Source: Internet
Author: User

Memory management

For this, in fact, is now the arc mode, the normal state does not have to manually release memory, so if it is not to interview Ah, installed force or solid foundation, first do not look or understand the next can, because like the interview, some interviewers want to see your foundation, some people will ask, now work is basically not used.

Learning Goals

1. Mastering the principles of memory management

2. Master Manual Memory Management

===============================================

1. Knowledge that needs to be understood

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.

strcpy (P, "Hello world!");

Copies a string to the memory space pointed to by the pointer variable p.

Puts (p);

Print the string in the memory space that the P pointer points to.

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 two 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.

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've opened up a memory space where we have a very useful piece of 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 OC:

1.1.2 Reference count (Retaincount)

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 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.

If you use Alloc, copy, Mutablecopy, retain,new for an object, you must use the

The corresponding release or autorelease.

Popular point of view is who pollution who governance.

1.1.4 Objective-c's memory management follows this simple strategy:

1. You have the object you created, which means that the initial reference count of the object created (using methods such as Alloc,new,copy or mutalbecopy) is 1.

2. After sending the retain message to the object, you have the object, retaincount+1

3. When you do not need to use the object, send release or autorelease message discard this object

4. Do not send "discard" messages to objects that you do not own

1.1.4 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.1.5 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.

1.1.6 ARC executes a new rule

Developers cannot display calls to Dealloc; retain, release, Retaincount, and autorelease cannot be implemented and invoked.

Prohibit the use of @selector (retain), @selector (release) and so on.

Developers can still implement the Dealloc method if you want to manage resources instead of variables.

The custom Dealloc method in arc does not need to call [Super Dealloc] (which in fact causes a compilation error), and the compiler will force automatic linking to the parent class.

Developers can still use cfretain,cfrelease and other related methods for core Foundation-style objects.

Developers cannot use NSAutoreleasePool objects. Using @autoreleasepool under Arc, it is more efficient than nsatuoreleasepool.

To match the manual reference count, the method naming of the arc is limited:

Accessor methods cannot start with new, in turn: The developer cannot declare a property that has a new start, unless you specify a getter

@property NSString *newtitle;         //  @property (getter=thenewtitle) NSString *newtitle;   

1.1.7. Wild pointer error forms typically appear in Xcode as:Thread 1:exc_bad_access (code=exc_i386_gpflt) error. Because you have access to a piece of memory that is not yours.

2. Knowledge that needs to be remembered

2.1 Alloc and release

Create a Dog class

@interface dog:nsobject  @end  @implementation Dog  -(void) dealloc  {    NSLog (@ "dog dealloc");    [Super Dealloc];  }  @end

The destructor in Delloc, when the object is destroyed, automatically calls this method, and we rewrite this method here.

In the main function, write the following code:

int Main (intconstChar * argv[])  {    @autoreleasepool {        *dog = [[Dog alloc] init];     }    NSLog (@ " program is about to exit ");     return 0 ;  }

From the terminal printing information, the program is about to exit this print, the dog Dealloc has been printed, 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 (intconstChar * argv[]) {    @autoreleasepool {        *dog =      [[Dog alloc] init]; [Dog release];     }    NSLog (@ " program is about to exit ");     return 0 ;}

Execute the program again, from the print can be seen 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.

2.2 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.

Use in composite of class 2.3

In the code above, add the person class

@interface Person:nsobject {//a man with a dog (holding a dog)Dog*_dog; }  - (void) Setdog: (Dog *) Dog; -(DOG *) Dog; @end @implementation Person/*version 1 (problematic) the person does not really 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 not to be released and memory leaks.  -(void) Setdog: (dog *) Dog {_dog = [dog retain]; }    */   /*version 3 (problematic) if you would 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]; }

Mrc:

Golden rule:

As long as the alloc/retain/copy/mutablecopy,new is used, the object is created

Then you have to release it using release,

——— summary sentence is: Who creates, who is responsible for releasing

Retain-makes the object reference count +1, if the pointer needs to go to hold this object

Need to use retain

Retaincount: Returns the reference count value of an object

Release:-Make the object reference count-1 instead of releasing the object

Dealloc: This method is automatically called when the object is destroyed (that is, when Retaincount is 0)

Mrc:

2.4 @property retain,assign,copy unfold

2.4.1 retain unfold

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

@property (nonatomic, retain) Dog *dog;

The following will be expanded:

-(void) Setdog: (dog *) dog{  if (_dog == [dog retain]; }}

2.4.2 Assign unfold

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

@property (nonatomic, assign) Dog *dog;,assign is directly assigned, it expands as follows:-(void) Setdog: (Qfdog *=  Dog;}

2.4.3 Copy Expand, copy the original object

Copy more for string

@property (nonatomic, copy) NSString *name;           Expand as follows:-(void) SetName: (NSString *) name{  if (_name! = = [name copy]; }}

2.4 String Memory Management

2.4.1 Memory management of strings

For strings, the golden rule is highly non-compliant! (If you look at the reference count from a string, it's a mess!) It's just a representation! In fact, the internal still follow!!

What we have to do is, we still abide by our golden rule!

Therefore, if it is nsstring, our property format is written as follows: @property (nonatomic, copy) NSString *name;

2.4.2 Copy and Mutablecopy

2.5 Memory management of arrays

Conclusion

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).

2.6 Autorelease and Autoreleasepool

In the main function, write the following code:

intMainintargcConst 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 destroys NSLog after the reference count of the dog is printed (@"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.

2.7 Plus method of memory management

The object we created with the Add method, without our release, is because the implementation within the class uses autorelease, deferred release

Add an Add method to the dog's declaration

+ (ID) dog;

Implemented in the implementation of the Dog class

+ (ID) dog

{

Note that this should not be written in release, if it is release, then just created destroyed, using autorelease, so that the ownership of the object to the automatic release pool, as long as the automatic release of the pool is not destroyed, the dog object will not be destroyed.

return [[[Dog alloc] init] autorelease];

}

2.8 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. Since the auto-free pool finally uniformly destroys objects, if an operation is more memory intensive (objects are more or objects occupy more resources), it is best not to put them into the auto-release pool or consider putting them into multiple auto-release pools;
    4. The static methods in the class library in OBJC generally do not need to be released manually, and the Autorelease method is called internally.

=====================================

Keywords in arc mode:

__strong/__weak/__unsafe_unretain

Developers need to properly modify variables. Use the following format to modify the variable declaration.

Class name * modifier variable name

For example:

       MyClass * __weak myweakreference;          

The corresponding @property parameters are

Strong/weak/unsafe_unretain

__strong: A strong reference, equivalent to the retain under the MRC, refers to a decision on the object

there is, by default.

__weak: A weak reference, a possession that does not have a decision against the object, is equivalent to the MRC

Assign, the pointer is assigned nil after the object is disposed.

__unsafe_unretain: Weak reference, refers to the object does not have the decision to occupy, equivalent to the MRC under the Assign, after the object is released, the pointer is a dangling pointer (will not be assigned to nil), you can appear wild pointers, not recommended to use.

@property (nonatomic, strong) xxx

Set similar to retain expand [name retain]

@property (nonatomic, weak) xxx

Similar to assign

@property (nonatomic, unsafe_unretain) xxx

Similar to assign

iOS Development-memory management

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.