OC Memory Management
First, the basic principle
(a) Why memory management
Because the memory of the mobile device is extremely limited, so the memory of each app is also limited, when the app consumes more memory, the system will issue a memory warning, you need to reclaim some no longer need to continue to use the memory space, such as recycling some of the unused objects and variables.
Managed Scope: Any object that inherits NSObject and is not valid for other basic data types.
The essential reason is that because objects and other data types are not in the same storage space in the system, other local variables are mainly stored in the stack, and objects are stored in the heap, and when the code ends, all the local variables involved in the code block are reclaimed, and pointers to the objects are recycled, and the object has no pointers pointing to it. But it still exists in memory, causing a memory leak.
(ii) Basic structure of the object
Each OC object has its own reference counter, which is an integer representing the number of times the object has been referenced, that is, how much of the object is now being used. When an object has just been created, the acquiescence counter value is, and when the value of the counter becomes 0 o'clock, the object is destroyed.
Within each OC object, there is a dedicated 4-byte storage storage space to store reference counters.
(iii) Role of reference counters
The only way to determine whether an object should be recycled is if the counter is 0, or if not 0.
(iv) operation
Send a message to the object for the corresponding counter operation
Retain message: Use counter +1 to change the method to return the object itself
Release message: Using Counter-1 (does not mean releasing objects)
Retaincount message: Get the object's current reference counter value
(v) Destruction of objects
When an object's reference counter is 0 o'clock, it is destroyed and the memory it occupies is replayed by the system.
When the object is destroyed, the system automatically sends an DEALLOC message to the object, typically overriding the Dealloc method, where the associated resources are freed, dealloc like the object's "last words." Once the Dealloc method is overridden, "super dealloc" must be called and placed in the last call of the code block (the Dealloc method cannot be called directly).
Once the object is recycled, the occupied storage space is no longer available, and persistent use causes the program to crash (wild pointer error).
Second, the relevant concepts and use of attention
Wild pointer error: Access to a piece of bad memory (already recycled, unusable memory).
Zombie objects: Objects that occupy memory have been reclaimed, zombie objects can no longer be used. (Turn on zombie object detection)
Null pointer: No pointer to anything (storage is 0,null,nil), sending a message to a null pointer does not give an error
Note: You cannot use "p retain" to revive a zombie object
Three, memory management principles
(i) Principles
As long as someone else is using an object, the object will not be recycled;
As long as you want to use this object, then you should let the object reference counter +1;
When you do not want to use this object, you should let the object reference counter-1;
(ii) who created, who release
(1) If you create an object by Alloc,new,copy, you must call the release or Autorelease method
(2) You're not the one who created it.
(iii) who retain, who release
Whenever you call the retain, whatever the object is generated, you're going to call release.
(iv) Summary
The beginning and end, there should be a minus, once let an object counter plus 1, you should let it in the last 1
Iv. Memory Management Code specification
(a) If alloc is called, it will have to have release (Autorelease)
(ii) Code specification for the Set method
(1) Basic data type: direct copy
-(void) Setage: (int) Age
{
_age = age;
}
(2) OC Object Type
-(void) Setcar: (Car *) car
{
1. First to determine whether the new object is passed in
if (car! = _car) {
2. Do a release of the old object once
[_car release];//if not on the object, then no effect
3. Do a retain on a new object
_car = [car retain];
}
}
(iii) Code specification for the Dealloc method
(1) Be sure to [Super Dealloc], and put it to the last
(2) Do a release operation on other objects owned by Seld (current)
-(void) dealloc{
[_car release];
[Super Dealloc];
}
V. Parameters of the @property
(1) Memory management related parameters
Retain: Release on object value, Retain new value (for OC object type)
Assign: Direct Assignment (default, for non-OC object types)
Copy:release old value, copy new value
(2) whether to generate a set method (not generated if it is a read-only property)
Readonly: Read only, generate getter declarations and implementations
Readwrite: Default, generate both setter and getter declarations and implementations
(3) Multithreading management (Apple has blocked multi-threaded operation to some extent)
Nonatomic: High performance, generally use this
Atomic: Low Performance
(4) name of the set and get methods
Modify the set and get methods, primarily for Boolean types, because method names that return Boolean types are usually preceded by IS, modifying the getter that the name typically uses in the Boolean type
@property (setter = Setabc,getter = Isrich) BOOL rich;
BOOL b=p.isrich;//Call
Vi. Circular reference problems in memory management and solutions
Case: Each person has an ID card, each ID card corresponding to a person, can not use #import way to each other, which forms a circular reference
New Keywords: @class class name;--solve circular reference problems, improve performance
@class just tell the compiler to handle the following name as a class when compiling.
(1) The role of @class: Declaring a class that tells the compiler that a name is a class
(2) Specification of a class referenced in development
1) Use @class in the. h file to prove the class
2) Use #import to include everything in the class when you really want to use it in. m files
(3) Solutions for circular references at both ends
Note: One end uses retain, and one end uses assign (no more release in Dealloc using assign)
Seven, Autorelease
(i) Basic usage
(1) The object is placed in an auto-release pool
(2) When the automatic release pool is destroyed, all objects inside the pool will be released once
(3) The object itself is returned
(4) When the Autorelease method is called, the object's counter is unaffected (destroyed)
(ii) Benefits
(1) no longer need to care about the time the object was released
(2) No need to worry about when to call release
(iii) Use of attention
(1) Occupy large memory objects, do not use autorelease, should use release to precisely control
(2) Use of Autorelease for objects with small memory footprint, not much impact
(d) Wrong wording
(1) Continuous Call multiple autorelease, release the pool Destroy two times release (-1)
(2) Alloc is called after the Autorelease, and then the release is called
(v) automatic release of the pool
(1) During the operation of the iOS program, countless pools are created that are present in the stack structure (advanced
(2) When an object calls Autorelease, the object is placed in the release pool at the top of the stack
(vi) How the automatic release pool is created
(1) How to create iOS5.0 before
NSAutoreleasePool *pool = [NSAutoreleasePool alloc]init];
[Pool release];
(2) After iOS5.0
@autoreleasepool
{
Start on behalf of Create auto release
。。。。。
}//end represents destruction of the auto-release pool
(vii) Autorelease Note
(1) The system comes with the method, if does not contain alloc new copy and so on, then these methods return objects are autorelease such as "NSDate date";
(2) In development often write some kind of method to quickly create a Autorelease object, do not use the class name directly when creating objects, but use self
Eight, ARC memory management mechanism
(i) Arc's judging criteria
The object is freed as long as no strong pointer is directed to the object
(ii) Pointer classification
(1) Strong pointer: By default, all pointers are strong reference pointers, keyword strong
(2) Weak pointer: __weak keyword-decorated pointer
Declare a weak pointer as follows:
__weak person *p;
In arc, the weak pointer is emptied as long as the object pointing to the weak pointer does not exist.
__weak person *p=[person alloc]init];//unreasonable, the object once created is released, the object is released, ARC will automatically empty the pointer.
Instead of using retain in the property, the arc uses strong and no more [super Dealloc] in Dealloc.
@property (Nonatomic,strong) dog*dog;//means that the generated variable _dog is a strong pointer, equivalent to the previous retain
If it is a weak pointer, replace it with weak and do not need to add __.
Three Summary of features of Arc
(1) not allowed to call release, Retain,retaincount
(2) Dealloc not allowed to be rewritten, but not allowed to invoke [super Dealloc]
(3) Parameters of @property
Strong: Equivalent to the original retain (used for OC object type), the member variable is a strong pointer
Weak: Equivalent to the original assign (for OC object type), member variable is weak pointer
Assign: For non-OC object types (base type)
(iv) Supplementary
Make the program compatible with ARC and non-arc parts. Transition to non-arc-fno-objc-arc to arc,-f-objc-arc
ARC also needs to consider circular reference problems: one end uses retain and the other end uses assign
Note: strings are special objects but do not need to be released manually with release, this string object is autorelease by default and does not require additional memory to be used for the pipe.
OC Memory Management