Block for iOS

Source: Internet
Author: User

Block for iOS

Source: codingZero

Introduction

IOS programmers who do not use block, not qualified programmers
After learning block, you don't want to use tedious agents anymore.
Block is not as difficult as you think, do not be afraid, do not be afraid, brave to try
The author entered the world of ARC in iOS, so I will only use it in the ARC environment.

What is block?

A block is actually a code block. It encapsulates the code you want to execute in this code block and calls it when necessary. Is the block an OC object? The answer is yes.

 

 

From official documents

"Block is an OC object, which means it can be added to a set, such as NSArray and NSDictionary"

Block definition block assignment

Format: block = ^ return value type (parameter list ){}

Task requirement: click "new" in the upper-right corner of controller A to jump to Controller B. After adding A contact to Controller B, click "save" to return to Controller A and display the newly added contact to the list.

The question is, how can we transmit data from controller B to Controller?

That's not easy. Controller A directly transmits the contact array to Controller B. Controller B creates A new contact and adds it to the array. Then, Controller A is returned, refresh the table in the viewWillAppear method of Controller.

The method is feasible, but I have to say that it is quite low. Controller B is used to add Contacts. As for the contact array, you do not need to care about it. Therefore, do not pass the array to Controller B.

All controller B has to do is create A contact and pass the contact object to controller A. As for what Controller A will do after getting the contact, it is A and has nothing to do with controller B.

As you can see, many people may already think of proxies. Yes, they can,... Yes ..., Controller B defines the protocol, declares the proxy method, and controller A sets the proxy, complies with the Protocol, and then implements the proxy method. Controller B calls the proxy method in the appropriate place, in A slot, which is troublesome, I don't want to write any code, so I should go back to farming.

Now, let's get started.

Use block to transmit data block common minefield-circular reference

Block has a special point of attention. What is circular reference? You reference me, I reference you, no one is released, the object cannot be destroyed, the memory is occupied

Let's look at an example of circular reference.

 

 

 

Pay attention to the console output. When "cancel" is clicked, controller B is destroyed and the dealloc method is called.

Open the commented-out code and run it again.

 

 

 

Click the "cancel" button. B is removed, but the dealloc method is not called. Therefore, controller B is not destroyed. why?

The block object is assigned to the attributes of the B controller. Therefore, B will have a strong reference to the block, and the self (B controller object) is used in the block ), block will capture the used external variables. Therefore, block also has a strong reference to Controller B, which eventually leads to circular reference and no one can release it.

Circular reference solution

How can circular references be solved? It's easy, just a line of code.

 

 

 

Replace self with weakSelf, and the block will not strongly reference self.
In the figure, _ weak can also use _ unsafe_unretained. The difference is that the Pointer Modified by _ weak is automatically set to nil after the object is destroyed, the _ unsafe_unretained modified pointer will become a wild pointer after the object is destroyed. For security purposes, we recommend that you use _ weak

Block Classification
Block can be divided into three types
 
 
  • NSStackBlock: Stack block
  • NSMallocBlock: heap block
  • NSGlobalBlock: Global block
1. Stack block

Features: the lifecycle is controlled by the system, and function return is destroyed.
The block that uses local variables and member attribute variables without strong pointer references is stack block.

A. local variables are used (figure 1). I is a local variable. The block is printed directly in NSLog and is not referenced by the pointer.

 

 

Figure 1

B. Use the member property variable (figure 2). name is the member property.

 

 

Figure 22. Heap block

Features: destroy without strong pointer reference, and the life cycle is manually managed by the programmer
Stack block if a member attribute reference with strong pointer reference or copy modification is copied to the heap and changed to heap block.

A. Strong pointer reference (Figure 3). The block is referenced by testBlock. testBlock is a strong pointer of the block type (strong pointer is used by default in the ARC environment)

 

 

Figure 3

B. copy modified member attribute reference (Figure 4)

 

 

Figure 43. Global block

Features: long life, how long is it? Long and long, people are at the tower (the application is at it)
External variables are not used, or blocks that only use global variables or static variables are global blocks.

For a global block, there is no pointer reference, and it does not matter whether the block type member attributes are modified using assign, weak, strong, or copy. However, global block is rarely used in development, so do not use weak or assign

A. external variables are not used (figure 5), and the block in does not use external variables, so even weak modification is also a global block (for example, weak is not used in development, I have used it)

 

 

Figure 5

B. Only global variables, static variables (figure 6), str are global variables, str1 is static variables, and only one of them is a global block.

 

 

Figure 6

Category summary
1. Do not use external variables or use blocks that only use global variables or static variables as global blocks. The lifecycle starts from creation to the end of the application.
2. The block that uses local variables and member attribute variables is a stack block. The lifecycle is controlled by the system, and function return is destroyed.
3. A block referenced by a member attribute with strong pointer reference or copy modification will be copied to the heap as a heap block. If there is no strong pointer reference, the block will be destroyed, and the lifecycle will be controlled by the programmer.

Block capture of external variables

A. Basic data type-local variables
The block copies the value of the variable as a constant. Modifying the value of the variable outside the block does not affect the block, and the block cannot be modified internally.

If you want to modify the value of the external variable I, you can add the keyword _ block before int I = 0. In this case, I is equivalent to a global variable or a static variable.

 

 

 

The external variable I is changed from 0 to 1, and the internal printing of the block is still 0.

 

 

 

B. Basic data types-static variables, global variables, and member attribute variables
The block directly accesses the variable address. You can modify the variable value within the block. After the external variable is modified, the block will also change internally.

In the figure, _ k is the member attribute variable. The initial values are I = 10, j = 20, k = 0. The block only performs an auto-increment operation on I, j, and k, the output is I = 12, j = 22, k = 2, so the external auto-increment operation also affects the internal, that is, accessing the same memory address

 

 

 

C. pointer type-local variable
The block copies a pointer and strongly references the object indicated by the pointer. the pointer cannot be modified internally.

The Code commented out in the figure tries to modify the pointer pointing, so an error is reported (if you want to modify the pointer, add _ block to the Front), but you can modify the value of the indicated object, for example, str changes from "abc" to "abcdef"

 

 

 

D. pointer type-global variables, static variables, and member variables
The block will not copy the pointer, but it will strongly reference this object. You can modify the pointer pointing internally. The block will strongly reference the object to which the member attribute variable belongs. This is why the block attribute uses self internally. why does xxx cause circular reference?

In the figure, str2 is the member attribute. Because NSString is immutable, we can see from the print results that the reference of the external pointer variable is modified inside the block, pointing to the new string.

 

 

At this point, I have shared my understanding of block with you, and you are welcome to add and correct it at any time.

Q: customized IT education platform, one-to-one service, Q & A. Official Website for developing programming social headlines: www.wenaaa.com

QQ Group 290551701 has gathered many Internet elites, Technical Directors, architects, and project managers! Open-source technology research, welcome to the industry, Daniel and beginners interested in IT industry personnel!

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.