Ios Block usage

Source: Internet
Author: User

Ios Block usage
Ios4.0The system has started to support block. During the programming process, blocks is considered as an object by Obj-C, which encapsulates a piece of code that can be executed at any time. Blocks can be used as a function parameter or return value, and it can include an input parameter or return value. It is similar to the traditional function pointer, but there is a difference: blocks is inline and it is read-only for local variables.

The following is the theoretical part:

1. block Definition

 
1 // the declaration and implementation are written together, just as the declaration of the variable achieves int a = 10; 2 int (^ aBlock) (int, int) = ^ (int num1, int num2) {3 4 return num1 * num2; 5 6}; 7 // the declaration and implementation are separated, just as the variable is first declared and then int a; a = 10; 8 int (^ cBlock) (int, int); 9 cBlock = ^ (int num1, int num2) 10 {11 return num1 * num2; 12 };
 

 

A blocks object named aBlock is defined and carries the following information:

1. aBlock has two parameters of the int type;

2. the return value of aBlock is of the int type;

3. the right side of the equation is the specific implementation of blocks;

4. ^ along blocks declaration and implementation mark (keyword );

Of course, you can define other types of blocks. E. g: no return value, no form parameter, etc;

1         void (^bBlock)() = ^()2         {3             int a = 10;4             printf(num = %d,a);5         };    

2. blocks access permission

Blocks can access local variables but cannot be modified.

1         int a = 10;2         int (^dBlock)(int) = ^(int num)3         {4             a++;//not work!5             return num * a;6         };

The reason cannot be modified here is determined during the compilation. during compilation, the compiler copies the value of a to the block as a new variable (assuming that it is a' = 10 ), in this case, A' and a are irrelevant.

This is the value transfer in the function. If you want to modify it, add the keyword __block or static.

 

1         __block int a = 7;2         int (^dBlock)(int) = ^(int num)3         {4             a++;// work!5             return num * a;6         };

3. block call

Block calling is like calling a function. E. g:

1 int c = aBlock(10,10);
  bBlock();

 4. block applications

If we are familiar with the value delivery by proxy, we may love and hate it! First, create the model A page to push the B page. If you pass the value of page A to page B, the attribute and single-Case values can be done! However, if the value of page B is transferred to page A during the Pop process, you can use A singleton or proxy! Speaking of proxy, It is very troublesome to declare the protocol and create a proxy first. We often need to write a lot of code between two pages to pass a value. The code changes the overall order of the page and reduces readability. Therefore, block is an optimization solution!

5. block memory management

 

The block itself can retain, and release like an object. However, when a block is created, its memory is allocated to the stack instead of heap. The domain itself belongs to the scope at the time of creation. Once block is called outside the scope at the time of creation, the program will crash. For example, the following example. I created a block in view did load:
 
  1. -(Void) viewDidLoad
  2. {
  3. [SuperviewDidLoad];
  4.  
  5. Int number = 1;
  6. _ Block = ^ (){
  7.  
  8. NSLog (@ number % d, number );
  9. };
  10. }
The block is called in a button event:
 
  1. -(IBAction) testDidClick :( id) sender {
  2. _ Block ();
  3. }
After I press the button, the program will crash. The solution to this problem is to call the copy method when creating the block. Copy will move the block from the stack to the stack, so you can use this block elsewhere ~ The modification code is as follows:
 
  1. _ Block = ^ (){
  2. NSLog (@ number % d, number );
  3. };
  4.  
  5. _ Block = [_ blockcopy];
Similarly, when you place the block into the collection class, you cannot use the block elsewhere if you directly place the generated block into the collection class, you must copy the block. However, the Code looks strange:
 
  1. [Array addObject: [[^ {
  2. NSLog (@ hello !);
  3. } Copy] autorelease];

6. circular reference
For non-ARC objects, to prevent circular references, we use _ block to modify the objects used in the Block:
For ARC, to prevent circular references, we use _ weak to modify the objects used in the Block. The principle is: in ARC, if the _ strong modifier's automatic variable is referenced in the Block, it is equivalent to the Block's reference count for this variable + 1.
This is actually a small derivative of the first point. When using member variables inside a block, such
 
  1. @ Interface ViewController: UIViewController
  2. {
  3. NSString * _ string;
  4. }
  5. @ End
Creating a block:
 
  1. _ Block = ^ (){
  2. NSLog (@ string % @, _ string );
  3. };
Here, the _ string is equivalent to self-> _ string; then the block will retain the internal object once. That is to say, self will be retaken once. When self is released, it will be released only after the block is released, but the block must be released only after self's dealloc. As a result, it is transformed into a circular reference, resulting in Memory leakage.
The solution is to create a local variable of _ block scope and assign self to it. This local variable is used for value within the block. Because the variables marked by _ block are not automatically retain.
 
  1. _ Block ViewController * controller = self;
  2. _ Block = ^ (){
  3. NSLog (@ string % @, controller-> _ string );
  4. };

 

 

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.