Introduction to Block and introduction to block

Source: Internet
Author: User

Introduction to Block and introduction to block

1. About Blocks

Block literally refers to the features introduced by Apple from iOS4.0 and Mac OS X 10.6.

Block is an object in Objective C language, but it is different from NSObject. Block is a special Objective C object.

 

The Block object provides a C language and a C-derived language (such as Objective-C and C ++) to create an expression as a special function. In other languages and environments, a block object is sometimes called a closure )". Here, they are generally written as "blocks" unless in some scope they are easily confused with the block code of the Standard C expression.

There are many definitions for closure. closure is a function that can read internal variables of other functions.

The "^" symbol can be called the caret ['k character r character t] or the delimiters.

 

 

Return Value (^ block Object Name) (parameter list type) = ^ (parameter list) {code in the block object };

 

2. Usage

 

1) Simple callback process, no need to implement and call a function (UIView animation)

2) concise code to reduce redundant code

3) combined with GCD

Use: UIView animation, presentViewController, and ASI

 

3. Declare and create a Block

Declared Block reference No parameter no response no parameter yes response no parameter no response

Define Block

Use Block

The typedef declaration is short for creating a new name or a type alias for an existing type. It is used in struct definition, arrays, and other places.

If the return value or parameter is Block

Snippet code snippet

 

4. Block Variable Access Management

1) local variables

Local variables are read-only in the Block. When Block is defined, the value of the copy variable is used as a constant in the Block. Therefore, even if the value of the variable changes outside the Block, the value of the variable in the Block is not affected.

 

2) _ Block modified Variables

If you want to modify the local variable declared outside the block, add _ block to the variable.

 

3) Static modifier or global variable

Because the addresses of global or static variables in the memory are fixed, the Block reads the variable value directly from its memory and obtains the latest value, instead of the constant copied during definition.

Block Variable. Variables modified by _ Block are called Block variables. Block variables of the basic type are equivalent to global variables or static variables, but the block variables of the object are not

 

5. Block memory management

Non-ARC

The Block is created on the stack by default, So if you leave the method scope, the Block will be discarded.

Block copy, retain, and release operations are different from NSObject copy, retain, and release operations:

As long as you implement a Block that does not reference the surrounding variables, it will be shown as NSGlobalBlock.

If a reference to a local variable is added, it is NSStackBlock.

If you use Block_copy () for an NSStackBlock object or send a copy message, the NSMallocBlock

 

1) NSGlobalBlock: The retain, copy, and release operations are invalid;

2) NSStackBlock: The retain and release operations are invalid. It must be noted that after the NSStackBlock function returns, the Block memory will be recycled, even if the retain is useless.

The easy mistake is [mutablepolicry addObject: stackBlock] (Supplement: Do not worry about this issue in ARC, because ARC will copy the instantiated Block to the stack by default) after the function exits the stack, the stackBlock obtained from mutablepolicry has been recycled and changed to a wild pointer.

The correct method is to first copy [stackBlock copy] to the stack, and then add the array: [mutablepolicry addObject: [[stackBlock copy] autorelease]. Supports copy. After copying, a new NSMallocBlock object is generated.

3) NSMallocBlock supports retain and release. Although retainCount is always 1, the memory manager still increases and reduces the count. No new object will be generated after copy, but a reference is added, similar to retain;

4) Block_copy is equivalent to copy, and Block_release is equivalent to release;

5) the reference count retainCount and retainCount are always 1 for the Block, whether it is retain, copy, or release;

6) Try not to use retain for blocks, which is inconvenient to manage.

Block usage: UIView animation, presentViewController, and ASI

 

6. Block memory management for objc objects

Multiple object types: staticObj, globalObj, instanceObj, localObj, and blockObj

It mainly refers to the reference count of the variables used in the block when the block is copied.

1) Non-ARC

The locations of globalObj and staticObj in the memory are determined, so the reference count will not change during Block copy.

In Block copy, instanceObj does not directly add 1 to the reference count of the instanceObj object, but increases the self reference count by 1. Therefore, you can directly read and write the instanceObj variable in the Block.

When localObj is Block copy, the system automatically increases its reference count.

When blockObj is Block copy, the reference count does not change.

Use _ block to avoid circular reference _ block class * object = self

 

Void (^ block) (void) = ^ {

[BlockSelf doSomething];

};

 

7. Reference retain cycle cyclically

Loop Reference refers to the issue where two objects strongly reference each other, that is, retaing the other, and thus no one can release or leak memory. For example, when declaring a delegate, assign is generally used instead of retain or strong, because once you do so, it is likely to cause loop reference.

 

When will the release of second release the fist delloc in fist delloc be executed?

Execute when the fist reference count is 0, but now even if the fist is removed from the window. after the rootViewController is detached, it is released once, but it is found that second still retains the first reference. In the end, it still needs to release second to form a retain cycle of the delegate version, that is, loop reference.

 

Release _ pBlock when Will delloc be released in viewController delloc?

If the reference count of viewController is 0, the viewController is executed from the window. when the rootViewController is detached, it is released once, but the _ pBlock still retains the reference of viewController. In the end, it is still released. _ pBlock forms the retain cycle of the block version, that is, loop reference.

 

Block memory management

Under ARC

In ARC, blocks are automatically copied from the stack to the heap in the following situations:

1. The copy method is executed.

2. return value as a method

3. When you assign a Block value to a class or Blcok member variable of the id type with the _ strong Modifier

4. When the Cocoa framework method containing usingBlock in the method name or gdc api is passed.

 

Memory Management of objects in a Block

Under ARC

Only when the local variable is used, the block copies the pointer and strongly references the object pointed to by the pointer once. For other variables such as global variables, static variables, and block variables, the block does not copy the pointer and only strongly references the object pointed to by the pointer once.

The circular reference of a block, because when the block is copied to the stack, it will repeat the external variables it references. If the block references its host object, it is likely to cause loop reference. For example, self. myblock = ^ {[self doSomething];};

Use _ weak to avoid circular reference

 

Tips:

Memory is mainly divided

1. Stack-variables in the release are automatically allocated by the compiler, usually local variable function parameters.

2. Heap-generally released by the programmer. If the programmer does not release the heap, alloc may be recycled by the OS at the end of the program.

3. global (static): stores global variables and static variables. initialized global variables and static variables are stored in one area, uninitialized global variables and uninitialized static variables are in another adjacent area. -Static release after the program ends

People * p; People * p2 = nil;

4. There is also a special place to place constants. -NSString * lastName = @ "xue" is released after the program ends ";

LastName = @ "dkjs ";

5. Method Area

 

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.