Summary of black marathon _ video learning <objective-C> ---- 04 Memory Management, protocol, block, and arc

Source: Internet
Author: User

---------------------- ASP. NET + unity development,. Net training, and hope to communicate with you! ----------------------

 

I. Memory Management 1. Why should I use memory management:

The memory of mobile devices is extremely limited, and the memory occupied by each app is limited. When the app occupies a large amount of memory, the system will issue a memory warning. In this case, you have to recycle unnecessary memory space. For example, reclaim unnecessary objects and variables.

2. Management scope:

Any object that inherits nsobject is invalid for other basic data types (INT, Char, float, double, struct, Enum, etc.)

3. Reference Counter:

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 people are using this OC object, each OC object has a storage space of 4 bytes to store reference counters.

4. Reference Counter operations

Send a retain message to the object, so that the reference counter value is + 1 (the retain method returns the object itself)

Send a release message to the object. The reference counter value is-1.

You can send a retaincount message to the object to obtain the current reference counter value.

5. Object destruction

When the reference counter value of an object is 0, it will be destroyed and the occupied memory 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 an object.

Once the dealloc method is rewritten, you must call [superdealloc] and put it at the end of the call.

Do not directly call the dealloc Method

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

6. Rewrite the dealloc method.

For example, the dealloc Method for writing a person contains a car class.

-(void) dealloc{       [_car release];       [super dealloc];}
7. Concepts

Zombie object: the occupied memory has been recycled.

Wild pointer: pointer to zombie object (memory unavailable), will report error: EXC-BAD-ACESS: 0x20

Null Pointer: no pointer pointing to anything, but no error is reported. After p = nil, the error can be solved. There is no Null Pointer Error in OC.

Note: [p retaion] cannot be used to restore zombie objects. 8. 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, who release

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

4> conclusion

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.

9. Set Method Memory Management

If you have a member variable of the OC object type, you must manage the memory of this member variable. For example, there is a book * _ book

Implementation of the Set Method

-(void)setBook:(Book *)book{       if (book != _book) {              [_book release];              _book = [book retain];       }}

Dealloc method implementation

-(void)dealloc {       [_book release];       [super dealloc];}
[Email protected] Parameter

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

11. Cyclic reference in memory management and Solution

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 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 (the dealloc that uses assign does not need to be release) [email protected]:

When @ class is used to declare each other in two classes, no compilation error occurs. You can reference a class by using the @ Class class name. It indicates that it is a class.

13. Differences from # Import

1> # The import method contains all information about the referenced class, including the variables and methods of the referenced class. The @ class method only tells the compiler that. in the H file, B * B is only a class declaration. You do not need to know the specific information in this class. When the implementation file is actually used, to view information in Class B.

2> if there are hundreds of header files # import the same file, or these files are # improt in sequence, once the header file is slightly changed, all the classes referenced in this file need to be re-compiled. This efficiency can be imagined. In contrast, this problem will not occur in the @ class method.

3> In the. m implementation file, if you need to reference the object variable or method of the referenced class, you also need to use the # import method to introduce the referenced class.

4> loop retain

For example, if object a retests object B, object B retests object.

In this way, object A and object B will never be released.

Solution:

When the two ends reference each other, one end should use retain, and one end should use assign

14. 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 syntax

(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> automatic release of the pool Creation Method

(1) how to create an instance before IOS 5.0

NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init]; ''' [pool release]; // [pool drain]; used for MAC (2) @ autoreleasepool after ios5.0 {// start to create an automatic release pool...} // end to destroy the automatic release pool

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

 

Ii. protocol1. Protocol definition
@ Protocol name <nsobject> // method declaration list ...... @ end
2. How to comply with the agreement

1> class Compliance Agreement

@ Interface Class Name: parent class name <protocol name 1, protocol name 2> @ end

2> agreement compliance

@ Protocol name <other protocol name 1, other protocol name 2> @ end
3. Keyword of method declaration in the Protocol

1> @ required (default)

Implementation required. If not, a warning will be issued.

2> @ optional

Implementation is not required. How can we avoid warnings?

4. When defining a variable, restrict the objects stored in the variable to comply with a certain protocol.
Class Name <protocol name> * variable name; id <protocol name> variable name; nsobject <myprotocol> * OBJ; id <myprotocol> obj2;

If the protocol is not followed, the compiler will warn

The attribute declared in [email protected] can also be used as a protocol-compliant restriction.
@ Property (nonatomic, strong) class name <protocol name> * attribute name; @ property (nonatomic, strong) ID <protocol name> attribute name; @ property (nonatomic, strong) dog <myprotocol> * dog; @ property (nonatomic, strong) ID <myprotocol> dog2;
6. the Protocol can be defined in a separate. h file or a class.

1> if this Protocol is only used in a class, the protocol should be defined in this class.

2> if this protocol is used in many classes, it should be defined in a separate file.

7. the category can be defined in a separate. h and. M files, or in the original class.

1> generally, they are defined in separate files.

2> the classification defined in the original class only requires reading the syntax

// Defines a protocol named myprotocol @ protocol myprotocol <nsobject> // @ required requires implementation. If this parameter is not implemented, a warning will be issued. // @ optional does not require implementation-(void) test4; // @ required (default)
Iii. Introduction to block1.

What is a block? The type recommended by Apple is highly efficient and the code is saved during running. It is used to encapsulate and save code, a bit like a function. A block can be executed at any time.

Bolck and function similarity: (1) code can be saved (2) return values (3) parameters (4) Same calling method. Identifier ^

2. Basic usage

1> define block Variables

INT (^ sumblock) (INT, INT); // There are parameters. The return value type is intvoid (^ myblock) (); // No parameter. The return value type is null.

2> Use block to encapsulate code

3> block access to external variables

1) The block can access external variables;

2) by default, external local variables cannot be modified inside the block.

3) if the _ block keyword is added to a local variable, the local variable can be modified within the block.

4> Use typedef to define the block type (similar to the pointer to the function)

Typedef int(^MyBlock)(int ,int);

This type can be used to define block variables in the future.

MyBlock a,b;  a=^(int a,int b){return a-b;};MyBlock b2=^(int n1,int n2){return n1*n2;};
Iv. Introduction to arc1.arc

ARC is a new feature added since ios5, which completely eliminates the hassle of manual memory management. The compiler will automatically insert appropriate retain, release, and autorelease statements in appropriate places. You no longer need to worry about memory management, because the compiler handles everything for you.

ARC is a compiler feature, not a runtime feature of IOS. It is not similar to the garbage collector in other languages. Therefore, the performance of arc is the same as that of manual memory management, and sometimes it can be faster, because the compiler can also execute some optimized arc rules very easily: as long as there is a strong pointer variable pointing to the object, the object will be kept in the memory.

2. Arc judgment criteria:

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

3. 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 __.

4. 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)

 

 

---------------------- ASP. NET + unity development,. Net training, and hope to communicate with you! ----------------------

For details, see www.itheima.com.

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.