"oc" Memory Management

Source: Internet
Author: User

first, the basic principle (a) Why memory management is needed.

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 intrinsic reason is because the object and other data types in the system storage space is not the same, the other local variables are mainly stored in the stack, and the object is stored in the heap, when the code block at the end of the code block involved in all the local variables will be recycled, the pointer to the object is also recycled, the object has no pointer to point, 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 that indicates the number of times the object has been referenced, that is, how much of the object is now in use. When an object has just been created, the default counter value is 1, and the object is destroyed when the value of the counter changes to 0 o'clock.

Within each OC object, there is a dedicated 4-byte storage space to store the reference counter.

(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

Sends a message to the object for the corresponding counter operation.

Retain message: Make counter +1, change method return object itself

Release message: Make Counter-1 (does not mean to dispose of 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 consumes is reclaimed 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 storage space he occupies is no longer available, and sticking to it can cause the program to crash (a 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 retaion] 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

As long as you call the retain, no matter how the object is generated, you have to call release

(iv) Summary

After the beginning and finish, there should be a reduction in addition. Once you have an object counter plus 1, you should make it last-1.

Iv. Memory Management Code specification (a) If alloc is called, it must 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 determine whether the new incoming object

if (Car!=_car)

{

2. Do a release of the old object once

[_car release]; If there are no old objects, there is 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 self (current)

-(void) dealloc

{

[_car release];

[Super Dealloc];

}

v. Parameters of the @property (1) memory management related parameters

Retain: Release old value for object, 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

Modifies the name of the set and get methods, primarily for Boolean types. Because a method name that returns a Boolean type is typically preceded by an IS, modifying a getter whose name is typically used in a Boolean type.

@propery (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) Declare the class using @class in the. h file

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

One end using retain, one end using assign (with assign in Dealloc and no more release)

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 in the pool are 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 Autorelease for objects that occupy less memory, with no significant impact

(d) Wrong wording

(1) Continuous Call multiple autorelease, release pool destroyed when the execution two times release (-1?). )

(2) After Alloc, the autorelease is called and then 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 post-exit).

(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 iOS 5.0 was created before

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

......

[Pool Release];//[pool drain]; for Mac

(2) After Ios5.0

@autoreleasepool

{//start on behalf of Create auto release pool

·······

}//end represents destroying the auto-release pool

(vii) Autorelease NOTE

(1) in the system's own method, if the Alloc new copy is not included, the objects returned by these methods 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 (a) ARC's judging criteria:

As long as no strong pointer points to the object, the object is freed.

(ii) pointer classification:

(1) Strong pointer: By default, all pointers are strong pointers, the 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 directly as long as the weak pointer is not in the object.

_ _weak person *p=[[person alloc] init];//unreasonable, the object once created is released, after the object is released, ARC automatically zeroed 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 member variable _dog is a strong pointer, equivalent to the previous retain.

If it is a weak pointer, replace with weak, do not need to add _ _.

(iii) ARC features summary:

(1) not allowed to call Release,retain,retaincount

(2) does not allow rewriting of dealloc, but does not allow calls to [super Dealloc]

(3) Parameters of @property:

Strong: Equivalent to the original retain (for OC object type), member variable is 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.

  

Tip: 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 managed.

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