IOS development-memory management, ios development Memory Management

Source: Internet
Author: User

IOS development-memory management, ios development Memory Management

Memory Management

For this article, we are actually using the ARC mode. Normally, we basically don't need to manually release the memory, so if you don't need an interview, installation, or solid skills, you just need to check it out or get to know it, because some interviewers may ask questions when they want to see your basics, but they will not be used in their work.

 

Learning Objectives

1. Master the principle of Memory Management

2. Master manual Memory Management

 

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

1. knowledge to be understood

1.1 Memory Management

1.1.1 C memory management and troubles

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

This is the dynamic memory allocation of C. We manually applied for 100 bytes of memory with the system; or the system opened up 100 bytes of space in the heap, return the first address of the space to the pointer Variable p.

Strcpy (p, "Hello World! ");

Copy the string to the memory space pointed to by the pointer Variable p.

Puts (p );

Print the string in the memory space pointed to by the p pointer.

Free (p );

After use, manually release the memory space with the system, or the system recycles the space.

The above is the simple memory management in C.

C memory management. We apply for it manually and release it manually. In this case, we only need to pay attention to two issues:

1. Apply for memory and release it after use. If it is not released, memory leakage will occur.

2. It cannot be released multiple times. If it is released multiple times, it will crash.

However, if the project is complex and requires the division of labor among dozens or hundreds of employees, the problem may easily occur.

For example, we have opened up a piece of memory space and stored a piece of useful data. However, this data is not used only in this Code, but also in multiple places of the program. The result is that even if I use this memory, I cannot release it because I am not sure whether other people need to use it elsewhere. Memory leakage is inevitable.

 

 

 

 

OC memory management:

1.1.2 reference count (retainCount)

For a dynamically applied memory, if one user (pointer) is used, add 1 to the memory counter. After the usage is complete, subtract 1 from the counter, when the reference count of this memory is 0, we will release it again. In this way, the above problem will be solved. OC is used to manage the memory by reference count.

 

 

 

1.1.3 golden rules for Memory Management

For reference counting, there is a set of prime rules for memory management:

The basic rule to apply is everything that 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, and new for an object, you must use

Corresponding release or autorelease.

The common saying is who pollutes and who manages.

 

 

 

1.1.4 objective-C Memory Management follows the following simple policy:

1. You have the object you created, that is, the initial reference count of the created object (using methods such as alloc, new, copy, and mutalbeCopy) is 1.

2. After you send a retain message to an object, you have this object, retainCount + 1

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

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

 

 

 

 

 

1.1.4 MRC and ARC

ARC Automatic Reference Counting, Automatic Reference Counting. xcode helps us manage the memory.

MRC Manual Reference Counting: Manual Reference Counting. we manage the memory manually.

 

Xcode 5.0 and later versions use the ARC mode by default,

 

 

 

 

 

 

 

1.1.5 how to change the project to MRC

Xcode5: The project is ARC when it is created. If we want MRC, we need to make the following settings.

Select project-target-Bulid Settings-Automatic Reference Counting to NO.

 

 

 

1.1.6ARCThe new rule is executed.

 

● Developers cannot display and call dealloc; they cannot implement and call retain, release, retainCount, and autorelease.

Do not use @ selector (retain) or @ selector (release.

Developers can still implement the dealloc method if you want to manage resources rather than variables.

The self-defined dealloc method in ARC does not need to call [super dealloc] (in fact, this will cause compilation errors). The compiler will force automatic link to the parent class.

Developers can still use CFRetain, CFRelease, and other related methods for Core Foundation-style objects.

 

● Developers are not allowed to use the NSAID or eleasepool object. @ Autoreleasepool is used in ARC, which is more efficient than NSAtuoreleasePool.

 

To work with manual reference counting, there are restrictions on the method naming of ARC:

● The accessor method cannot start with "new". In turn, the developer cannot declare an attribute starting with "new" unless you specify a getter

 

// Incorrect @ property NSString * newTitle; // correct @ property (getter = theNewTitle) NSString * newTitle;

 

 

1.1.7. The field pointer error format is usually shown in Xcode:Thread 1:EXC_BAD_ACCESS (code = exc_i1__gpflt)Error. Because you have accessed a piece of memory that does not belong to you.

 

2. knowledge 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 delloc destructor automatically calls this method when the object is destroyed. We will rewrite this method here.

Write the following code in the main function:

Int main (int argc, const char * argv []) {@ autoreleasepool {Dog * dog = [[Dog alloc] init];} NSLog (@ "the program is about to exit "); return 0 ;}

 

According to the terminal printing information, the program has printed the dog dealloc before exiting the printing. That is to say, the dog object has been destroyed before the program runs. This is ARC. xcode helps us manage dog objects.

Change ARC to MRC and execute the program. The dog object is not destroyed. Because we manage it manually now, we need to follow 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 format:

Int main (int argc, const char * argv []) {@ autoreleasepool {Dog * dog = [[Dog alloc] init]; [dog release];} NSLog (@ "the program is about to exit"); return 0 ;}

 

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

Note: release does not destroy objects, so the reference count of objects is reduced by 1. When the reference count of objects is 0, the dealloc method is automatically called to destroy objects.

 

 

 

2.2 retain and retainCount

Retain to keep the object, that is, add 1 to the reference count of the object.

RetainCount: prints the reference count of an object.

 

 

 

 

 

Used in 2.3 class combination

In the above Code, add the Person class

@ Interface Person: NSObject {// a Person who raises a Dog (holding a dog) Dog * _ dog;}-(void) setDog :( Dog *) dog; -(Dog *) dog; @ end @ implementation Person/* version 1 (problematic) people do not really hold the dog. If [Dog release] in the main function, reduce the reference count of dog by 1, and change to 0, and destroy dog. -(Void) setDog :( Dog *) dog {_ dog = dog;} * // Version 2 (problematic) if a person holds another Dog, the first dog will not be released and the memory will be leaked. -(Void) setDog :( Dog *) dog {_ dog = [dog retain];} * // * Version 3 (problematic) If you have a Dog, re-set the dog and perform release first. At this time, it is very likely that the dog will be destroyed, and then there will be no way to retain again. -(Void) setDog :( Dog *) dog {[_ dog release]; _ dog = [dog retain];} * // version 4 OK !, Standard syntax-(void) setDog :( Dog *) dog {if (_ dog! = Dog) {[_ dog release]; _ dog = [dog retain] ;}}- (Dog *) dog {return _ dog ;}- (void) dealloc {NSLog (@ "person dealloc"); // when a person destroys the dog object, the owner destroys [_ dog release]; [super dealloc];}

 

 

 

// MRC:

Golden rule:

If alloc/retain/copy/mutableCopy and new are used, an object is created.

You must use release for release,

--- To sum up one sentence: Who creates and who is responsible for release

Retain-make the reference count of the Object + 1, if the pointer needs to hold this object

Use retain

RetainCount: return the reference count value of the 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 the retainCount is 0 ).

 

 

 

 

 

MRC:

2.4 @ property retain, assign, copy expand

2.4.1 expand retain

In the above Code, the setter and getter methods of Person can also be written as follows using property.

@ Property (nonatomic, retain) Dog * dog;

It will be shown as follows:

- (void)setDog:(Dog *)dog{  if (_dog != dog)  {    [_dog release];    _dog = [dog retain];  }}

 

 

 

2.4.2 expand assign

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

@ Property (nonatomic, assign) Dog * dog;, assign is a direct value, then the following is displayed:-(void) setDog :( program dog *) dog {_ dog = Dog ;}

 

 

 

 

 

2.4.3 copy expansion: copy an original object

 

// Copy is mostly used for strings.

@ Property (nonatomic, copy) NSString * name; expand as follows:-(void) setName :( NSString *) name {if (_ name! = Name) {[_ name release]; _ name = [name copy] ;}}

 

 

 

 

 

 

 

 

2.4 string Memory Management

2.4.1 string Memory Management

// For strings, the golden rule is not followed! (If we look at the string reference count, it's a mess !) This is just a representation! Actually, it is internal !!

// What we need to do is that we still follow our golden rule!

Therefore, for NSString, our property format is as follows: @ property (nonatomic, copy) NSString * name;

 

2.4.2 copy and mutableCopy

 

 

2.5 Array Memory Management

 

 

 

 

Conclusion

1) when we create an array, the array will reference each object and Add 1

2) When the array is destroyed, the array will reference each object minus 1.

3) when we add an object to the array, we will add 1 to the reference count of the object.

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

In short, it is enough to manage who are contaminated and who are responsible (the array also complies with the memory management ).

 

 

 

 

2.6 autorelease and autoreleasepool

Write the following code in the main function:

Int main (int argc, const char * argv []) {@ autoreleasepool {Dog * dog = [[Dog alloc] init]; // The dog is not destroyed immediately, instead, the destroy is delayed, and the dog object ownership is handed over to autoreleasepool [dog autorelpool]; // This can be printed, because after printing the reference count of the dog, NSLog (@ "retainCount = % lu", dog. retainCount);} NSLog (@ "the program is about to exit"); return 0 ;}

 

Autoreleasepool is equivalent to an array. If an object sends the autoreleasepool message, the ownership of the object is actually handed over to autoreleasepool. When autoreleasepool is destroyed, all objects in autoreleasepool send a release message.

 

2.7 Memory Management

The objects created by using the add method do not need to be release because autorelease is used for internal implementation of the class to delay release.

Add an addition method to the declaration of the Dog class.

+ (Id) dog;

Implementation in the implementation of the Dog class

+ (Id) dog

{

Note: Do not write it as release here. If it is release, it will be destroyed when it is just created. Use autorelease to grant the ownership of the object to the automatic release pool, as long as the automatic release pool is not destroyed, the dog object will not be destroyed.

Return [[[Dog alloc] init] autorelease];

}

 

2.8 a brief summary of automatic memory release:

 

 

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

 

Keyword in ARC mode:

_ Strong/_ weak/_ unsafe_unretain

 

Developers must modify the variables correctly. Use the following format to modify the variable declaration.

 

Class name * modifier variable name

For example:

 

       MyClass * __weak myWeakReference;          MyClass * __unsafe_unretained myUnsafeReference; 

 

 

The corresponding @ property parameters are

Strong/weak/unsafe_unretain

 

_ Strong: indicates a strong reference, which is equivalent to a retain in MRC. the pointer determines the percentage of objects.

Yes. default value.

_ Weak: weak reference, pointer possession of the object is not determined, equivalent to

Assign. After the object is released, the pointer value is nil.

_ Unsafe_unretain: weak reference. The pointer does not have a decisive possession of the object. It is equivalent to the assign in MRC. After the object is released, the pointer is a suspension pointer (not assigned as nil ), A wild pointer may appear, which is not recommended.

 

@ Property (nonatomic, strong) xxx

// Set is similar to retain expansion [name retain]

@ Property (nonatomic, weak) xxx

// Similar to assign

@ Property (nonatomic, unsafe_unretain) xxx

// Similar to assign

 

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.