"OC" memory management, "oc 」

Source: Internet
Author: User

"OC" memory management, "oc 」
I. Basic Principles(1) Why memory management.

Because the memory of mobile devices is extremely limited, the memory occupied by each APP is also limited. When the app occupies a large amount of memory, the system will issue a memory warning, in this case, you need to reclaim some memory space that you do not need to continue using, for example, reclaim some objects and variables that are no longer in use.

Management scope: any object that inherits NSObject, which is invalid for other basic data types.

The essential reason is that objects and other data types have different storage spaces in the system. Other local variables are mainly stored in the stack, while objects are stored in the heap, when the code block ends, all the local variables involved in the code block will be recycled, and the pointer to the object will be recycled. At this time, no pointer is directed to the object, but it still exists in the memory, memory leakage.

(2) Basic Structure of Objects

Each OC object has its own reference counter, which is an integer that indicates the number of times the object is referenced, that is, how many items are currently using this object. When an object is created, the default counter value is 1. When the counter value is 0, the object is destroyed.

Each OC object has a 4-byte storage space to store reference counters.

(3) function of referencing a counter

The only basis for determining whether an object needs to be recycled is whether the counter is 0. If it is not 0, the counter exists.

(4) Operations

Send messages to an object and perform corresponding counter operations.

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

Release message: enables counter-1 (not to release objects)

RetainCount message: obtains the current reference counter value of the object.

(5) destruction of objects

When the reference counter of an object is 0, it will be destroyed and the memory occupied by it will be recycled by the system.

When an object is destroyed, the system automatically sends a dealloc message to the object. The dealloc method is rewritten to release related resources. dealloc is like the last words of the object ". Once the dealloc method is rewritten, you must call [super dealloc] and put it at the end of the code block (the dealloc method cannot be called directly ).

Once the object is recycled, the storage space occupied by it will no longer be available. sticking to it will cause the program to crash (the wild pointer is incorrect ).

Ii. Related Concepts and usage notes

Wild pointer error: access to a bad memory (recycled, unavailable memory ).

Zombie object: the occupied memory has been recycled, and the zombie object cannot be used again. (Enable zombie object detection)

Null Pointer: no pointer pointing to anything (the stored items are 0, null, nil). No error is returned when messages are sent to null pointers.

Note: [p retaion] cannot be used to restore zombie objects.

Iii. Memory Management Principles (1) Principles

As long as someone else is using an object, this object will not be recycled;

As long as you want to use this object, you should make the reference counter of this object + 1;

When you do not want to use this object, you should make the reference counter of the object-1;

(2) who created and who release

(1) If you create an object through alloc, new, and copy, you must call the release or autorelease method.

(2) You are not responsible for what you created.

(3) who retain and who release

If you call retain, you must call release no matter how the object is generated.

(Iv) Summary

There should be a reduction in the beginning and end. If you used to add 1 to an object counter, you should add it to the last-1.

Iv. Memory Management Code Specification (1) As long as alloc is called, there must be release (autorelease) (2) code specification of the set Method

(1) Basic data type: Direct Replication

-(Void) setAge :( int) age

{

_ Age = age;

}

(2) OC object type

-(Void) setCar :( Car *) car

{

// 1. first determine whether the object is a new object.

If (car! = _ Car)

{

// 2. Perform a release operation on the old object

[_ Car release]; // no effect if no old object exists

// 3. Make a retain for the new object

_ Car = [car retain];

}

}

(3) code specification of the dealloc Method

(1) be sure to [super dealloc] and put it to the end

(2) Perform a release operation on other objects owned by self (current ).

-(Void) dealloc

{

[_ Car release];

[Super dealloc];

}

5. @ property parameters (1) memory management parameters

Retain: Old value of the object release, new value of retain (applicable to OC object type)

Assign: direct value assignment (default, applicable to non-oc object types)

Copy: Old value of release, new value of copy

(2) Whether to generate the set Method (if it is a read-only attribute, It is not generated)

Readonly: Read-Only. Only getter statements and implementations are generated.

Readwrite: by default, the setter and getter statements and implementations are generated simultaneously.

(3) multi-thread management (Apple has blocked multi-thread operations to some extent)

Nonatomic: high performance.

Atomic: low performance

(4) Name of the set and get Methods

Modify the name of the set and get methods. It is mainly used for boolean type. The returned Boolean method name generally starts with "is", and the modified name is generally used in the getter Of The boolean type.

@ Propery (setter = setAbc, getter = isRich) BOOL rich;

BOOL B = p. isRich; // call

6. Issue and solution of loop reference in memory management

Case: each person has an ID card, each ID card corresponds to a person, and the # import method cannot be used to include each other. This forms a circular reference.

New keywords: @ class name; -- solves the problem of circular reference and improves performance

@ Class only tells the compiler to process the subsequent name as a class during compilation.

(1) @ class: declares a class and tells the compiler that a name is a class.

(2) reference a class specification during development

1) Use @ class in the. h file to declare the class

2) When the. m file is actually about to be used, use # import to include everything in the class.

(3) solution to circular reference at both ends

One end uses retain and the other end uses assign (dealloc does not need to release assign)

VII. autorelease (1) Basic usage

(1) objects will be placed in an automatic release pool.

(2) When the automatic release pool is destroyed, all objects in the pool are release once.

(3) the object itself will be returned.

(4) After the autorelease method is called, the counter of the object will not be affected (affected upon destruction)

(2) Benefits

(1) Don't worry about the time when the object is released

(2) No need to worry about when to call release

(3) usage notes

(1) do not use autorelease for objects that occupy a large amount of memory. Use release for precise control.

(2) The use of autorelease for objects with small memory usage has no significant impact.

(4) Incorrect writing

(1) autorelease is called multiple times in a row. When the release pool is destroyed, the release is executed twice (-1 ?)

(2) After Alloc, autorelease is called and then release is called.

(5) automatically release the pool

(1) When the ios program is running, countless pools will be created, all of which exist in the stack structure (Advanced and later.

(2) When an object calls autorelease, it is placed in the release pool at the top of the stack.

(6) how to create an automatic release pool

(1) how to create an instance before ios 5.0

NSAID utoreleasepool * pool = [[NSAID utoreleasepool alloc] init];

......

[Pool release]; // [pool drain]; for mac

(2) After Ios5.0

@ Autoreleasepool

{// Start indicates creating an automatic release pool

·······

} // End indicates that the automatic release pool is destroyed.

(7) autorelease note

(1) In the built-in methods, if alloc new copy is not included, all objects returned by these methods are autorelisted, for example, [NSDate date];

(2) Some class methods are often written in development to quickly create an autorelease object. When creating an object, do not directly use the class name, but use self

VIII. ARC Memory Management Mechanism (1) ARC judgment criteria:

As long as there is no strong pointer to the object, the object will be released.

(2) pointer classification:

(1) strong pointer: by default, all pointers are strong pointers, with the keyword strong

(2) weak pointer: Pointer Modified by the _ weak keyword

Declare a weak pointer as follows:

_ Weak Person * p;

In ARC, the weak pointer is cleared directly as long as the object to which the weak Pointer Points is no longer in use.

_ Weak Person * p = [[Person alloc] init]; // The object is released when it is created. After the object is released, the ARC automatically clears the pointer.

In ARC, the retain is no longer used at the property, but strong is used. In dealloc, [super dealloc] is not required.

@ Property (nonatomic, strong) Dog * dog; // indicates that the generated member Variable _ dog is a strong pointer, which is equivalent to the previous retain.

If it is replaced by a weak pointer, it is replaced by weak without adding __.

(3) Summary of ARC features:

(1) release, retain, retainCount cannot be called.

(2) dealloc cannot be rewritten, but [super dealloc] cannot be called.

(3) @ property parameters:

Strong: equivalent to the original retain (applicable to the OC object type). The member variable is a strong pointer.

Weak: equivalent to the original assign (applicable to the oc object type). The member variable is a weak pointer.

Assign: applicable to non-OC object types (basic types)

(4) Supplement

Make the program compatible with the ARC and non-ARC sections. Transition from non-ARC-fno-objc-arc to ARC-f-objc-arc.

ARC also needs to consider the circular reference problem: one end uses retain and the other end uses assign.

  

Tip: the string is a special object, but it does not need to be manually released using release. This string object is autorelease by default, and no extra memory is needed.

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.