iOS core language Objective C language-memory management

Source: Internet
Author: User

This share is intended for enthusiasts who are interested in developing partners for iOS and Apple products, or who are already working with iOS developers who want to be further promoted. If you have a high interest in iOS development, you can work with me on iOS development, learn together, and make progress together. If you are 0 basis, it is recommended that you first read my previously shared iOS development minutes to finish the C language series, and then at the beginning Objective C language learning, if you encounter problems can also discuss with me, in addition will be free to share their own compiled out of about 400G iOS learning video and learning materials, are dry! Can Sina Weibo private messages? Focus on geek James, look forward to working with you to learn and discuss together!! Due to the limited time, every day in the work of the study to share, inevitably there are shortcomings, but also hope that the way the big God!

Made by: Geek James

First, why to learn memory management
Memory for any hardware and software importance is self-evident, and as a hardware and user exchange of intermediate software, for memory requirements and how to use memory, how to allocate memory is very important, and objective C language is a superset of C language, memory and memory management is also of great importance. In iOS development, memory leaks can have a significant impact on the user experience, and Apple's hardware device's memory itself is small, so as an iOS developer, it's important to master memory management, but Apple uses the Arc compiler feature's memory management mechanism after Xcode 4.2. Greatly reduces the programmer's manual memory management, lets the programmer put the attention on the product logic, makes the Apple software PRODUCT to do better. While iOS development does not use MRC to manually manage memory, mastering the MRC's memory management mechanism is necessary to improve the development mindset and understand the memory management mechanism more deeply.

two, multi-language memory management
(1) Java language: Java Virtual machine and garbage collection mechanism.
(2) C + + language: Related C + + memory management is relatively complex, manual management, one of the programmer's pain points.
(3) Android: If you know Java, it will be easier to understand the memory management mechanism of the Android system. Similar to Java's garbage collection mechanism, the system has a rule to reclaim memory. There is a threshold for memory scheduling, and only below this value will the system press a list to shut down what the user does not need. This memory scheduling management method has a disadvantage, easy to cause memory leaks, so many Android phones often appear card machine and prompt memory full condition, the pain point of many Android users.
(4) Objective C language: Arc compiler management mechanism, programmers in the use of Xcode 4.2 or later software development, the compiler automatically in the appropriate location for memory release, do not need to manually manage.

iii. Heap and Stack
(1) Stack (operating system):
The release is automatically assigned by the operating system, storing the parameter value of the function, the value of the local variable, and so on. It operates in a way similar to a stack in a data structure (advanced back-out);

(2) heap (operating system):
Usually released by the programmer, if the programmer does not release, the program ends may be recycled by the OS, distributed in a manner similar to the list.

Four, Zombie object, wild pointer, null pointer
1. Zombie Objects
Objects that have been destroyed (objects that can no longer be used)

2. Wild Hands
Pointer to zombie object (memory not available)
Send a message to the wild pointer will report exc_bad_access error

3. Null pointer
There is no pointer to the storage space (there is nil, that is, 0)
There's no response to sending a message to the null pointer.
A common way to avoid wild pointer errors
After the object is destroyed, the pointer to the object changes to a null pointer

v. Memory management of Objective C language
The so-called memory management, is the memory management, involves the operation is:
(1) Allocating memory: Creating an object, for example, increases memory consumption
(2) Clear memory: such as destroying an object, can reduce memory consumption

Management scope of memory management
(1) Any object that inherits the NSObject
(2) Invalid for other non-object types (int, char, float, double, struct, enum, etc.)

only OC objects require the root cause of memory management:
OC objects stored inside the heap
Non-OC objects are generally placed inside the stack (the stack memory is automatically reclaimed by the system)

vi. manually managing memory for MRC
Manual Reference Counting: (MRC)

1. Reference counters
(1) The reference counter indicates how many people are using this object.
(2) When no one uses this object, the system reclaims the object, meaning that when the object's reference counter is 0 o'clock, the memory consumed by the object is reclaimed by the system.
(3) If the object's counter is not 0, the memory it consumes will not be recycled during the entire program run (unless the entire program has exited)
(4) Any object that has just been born, the reference counter is 1
(5) When you create an object using Alloc, new, or copy (Mutablecopy), the object's reference counter defaults to 1

2. Actions that reference counters
(1) Send an retain message to the object to make the reference counter value +1 (the Retain method returns the object itself)
(2) Send a release message to the object, you can make the reference counter value-1
(3) Send the Retaincount message to the object, you can get the current reference counter value (Retaincount sometimes inaccurate, it is recommended to use the Delloc method to verify whether the full memory release)
Note : Release does not represent destroying \ Reclaiming objects, just counters-1

3.dealloc Method
(1) When an object's reference counter value is 0 o'clock, the object is about to be destroyed, and the memory it consumes is reclaimed by the system.
(2) When the object is about to be destroyed, the system will automatically send an DEALLOC message to the object (therefore, from the Dealloc method has not been called, you can determine whether the object is destroyed)

rewriting of the Dealloc method
Usually rewrite the Dealloc method, release the related resources here, Dealloc is the object's last words
Once the Dealloc method is overridden, [super Dealloc] must be called and placed on the last side of the call

-(void)delloc{      [super delloc];}

4. Use note
The Dealloc method cannot be called directly
Once the object is recycled, the memory it consumes is no longer available, and sticking to it can cause the program to crash (wild pointer error).

5. Memory Management rules
(1) who created who release:
If you create an object by Alloc, new, or [mutable]copy], you must call release or Autorelease
Who Retain who release:

(2) If you call retain, you must call the release

Summarize:
Plus, there's a minus.
Once the object's counter +1, it must be at the end of the object counter-1, and finally override the Delloc method to check whether the memory is completely released.

6. Multi-Object Memory management
(1) Multi-object memory management rules:
As long as someone else is using an object, the object will not be recycled.
As long as you want to use this object, let the object's counter +1
When you no longer use this object, let the object's counter-1

(2) Setter method memory management rules:
Retain objects that need to be used
Objects prior to release
Release and retain are only required if the incoming object is different from the previous one

- (void)setRoom:(Room *)room{        // 避免过度释放(判断私有成员和局部成员是否相等)    if (room != _room)    {        // 对当前正在使用的车(旧车)做一次release        [_room release];        // _room = nil;        // 对新车做一次retain操作         _room = [room retain];    }}

Memory management rules for 3.DEALLOC methods

- (void)dealloc{    // 当人不在了,代表不用房间了    // 对房间做一次release操作    [_room release];    // 这样写逼格高一点  self.room = nil;    [super dealloc];}

[Email protected] Parameters

(1) memory management of the control set method
Retain:release old value, retain new value (for OC object)
Assign: Direct assignment, no memory management (default, for non-OC object types)
Copy:release old value, copy new value (typically used for NSString *)

(2) control need not generate set method
ReadWrite: Generate both the Set method and the Get method (default)
ReadOnly: Only the Get method is generated

(3) Multithreading management
Atomic: Low performance (default)
Nonatomic: High performance (this attribute is used in iOS development)

(4) control the name of the set method and the Get method
Setter: Set the name of the set method, there must be a colon:
Getter: Set the name of the Get method
If there is a bool type, the best way to modify the Getter method is: (getter = isxxx)
Note: Different types of parameters can be combined to use

(5) Circular Reference
When using the @property property to declare two objects, if you use retain at the same time, the memory will not be freed by referencing each other, and the solution is to use retain, one with assign.

8.autoreleasepool Auto-release pool
(1) An unlimited number of pools are created during the iOS program's operation. These pools are present in the stack structure (advanced), and when an object calls the Autorelease method, the object is placed on the top of the heap to release the pool.

(2) Autorelease is a memory management method that supports reference counting, as long as an autorelease message is sent to an object, the object is placed in an auto-release pool, and when the auto-free pool is destroyed, all objects inside the pool are released once

Note
This only sends the release message, and if the reference count (reference-counted) at the time is still not 0, the object will still not be freed.

(3)autorelease use precautions

    • is not placed in the auto-release pool code, it is automatically added to the auto-release pool
    • Sending autorelease outside of the auto-free pool is not added to the auto-release pool
      Autorelease is a method that is only valid if called in the auto-free pool.
    • If you write Autorelease, don't write release.
    • Whenever Autorelease is called in an auto-free pool, the object is placed in an auto-free pool
    • Automatic release of objects that are not suitable to occupy large memory in the pool
    • Do not call autorelease in succession, and do not put a lot of cyclic operations between the same @autoreleasepool
@autoreleasepool {// 创建对象时用autoreleasePerson *p  =[ [Person alloc]init]autorelease];}
// 类方法+(instancetype)person{return [[self alloc]init]autorelease];}
// 类工厂方法 +(instancetype)personWithAge:(intreturn [[[self alloc] initWithAge:age] autorelease];}
 -(void)dealloc{    NSLog(@"%s", __func__);    [super dealloc];}

vii. ARC Automatic reference count management memory
Automatic Reference Counting: (ARC)

Automatic reference counting, arc, can be said to be the biggest change and the most exciting change introduced by WWDC2011 and IOS5. Arc is a feature of the new LLVM 3.0 compiler that uses ARC to solve the problem of manual memory management that the vast majority of iOS developers resent.

1.ARC mechanism to judge the points of attention and advantages
The arc mechanism determines that there are several obvious signs under the arc mechanism:

    • Release method for calling object is not allowed
    • When overriding the Dealloc method of the parent class, you can no longer invoke [super Dealloc];

Arc's point of attention
-Arc is a compiler attribute, not a run-time attribute
-Arc is not a garbage collection in other languages, with an essentially different arc

Advantages
-Completely eliminates the cumbersome manual management of memory
-basically the ability to avoid memory leaks can sometimes be faster because the compiler can also perform some optimizations

2. Strong pointers, weak pointers
Strong pointers
All pointer variables are strong pointers by default
A pointer modified by __strong

*p1 = [[Person alloc] init]; __strong  *p2 = [[Person alloc] init];

Weak pointers
A pointer modified by __weak

__weak  Person *p = [[Person alloc] init];

3.ARC under single object memory management
(1) The local variable release object is subsequently released
(2) The empty pointer object is then released
(3) Default empty all pointers are strong pointers

A weak pointer requires a clear description:
Note : Never use weak pointers to save newly created objects

Circular reference issues under 4.ARC

As with MRC, when two objects are referenced to each other, there is a memory leak problem, the solution is: one with strong one with weak.

5.ARC under @property parameters

    • Strong: For OC objects, equivalent to retain in MRC
    • Weak: For OC objects, equivalent to assign in MRC
    • Assign: For basic data type, same as assign in MRC (default value)

6. How to convert MRC to Arc
The MRC Memory management mechanism was adopted prior to Xcode4.2, so it is possible to use a small tool in Xcode to convert arc when encountering MRC projects, but it is not guaranteed to be 100% successful, so the operation should be cautious.

Here's how:

·
·

How to use the hybrid arc and MRC:
Change to non-ARC-FNO-OBJC-ARC
Converted to arc,-F-OBJC-ARC (not used)

Above is my objective C memory Management system Summary and analysis, I hope to see this article you have some help, in addition, there is a need for information partners, Sina Weibo private message? Focus on geek James

Copyright NOTICE: This article for Bo Master original article, in order to be able to promote each other, learn from each other, please follow Sina Weibo: Geek James

iOS core language Objective C language-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.