A simple summary of block usage

Source: Internet
Author: User

one. Simple use of block1.block as a parameter to passDefine a block that does not have a return value without parameters, and take it as a parameter, let the system call, note: Here is the system in the call, not we call then why do we need to use block as a parameter? This leads to the use of blocks at this time: when you encapsulate a class, Some things are decided by the outside, but when done by the internal decision, (i.e. internal decision execution time, external incoming specific what to do)-this time you can use block as a parameter2.block as a return value to useThe following code, test is the method name, void (^) () This is the type of block, so it can be used, where the self.test is equivalent to the property of the Get method, followed by one () It is equivalent to executing block. You can also assign this block to the same type of Bock. The following code shows this. So the myblock with a parenthesis is executed, so that you can understand why the above self.test plus a parenthesis is executed.-- This reminds me that the Execute function in Swift is a point point, and adding () is the creation of the object execution function and so on, which is similar ....block when the return value of the use of thought: chained programming, the method call through the syntax link up, readability is very goodThe following is a simple demonstration of the use of block for chained programming to create a class inheritance nsobject named AddTool, that is, we will use it for the chain accumulation, its. h file as follows its. m file as follows: Then in the Viewcontroller class to make the call to run as follows, print the result, OK to complete!Two. Use of block inverse valueBlock can be used to reverse the value of the Controller interface. Use this way: Controller B passes the value to controller A, then the header file in controller B. H declares a block property and executes the block in the. m file of controller B. The code is represented as follows:
      • In the header file of B
@property (Nonatomic,strong) void (^myblock) (NSString *);Description: This defines a no return value, the name of the Block,block with the parameter NSString * is Myblock, which declares a function void test (int);--no return value, the argument is int, the function name is test.If a block that creates an int return value changes the above void to int and the block type here is the strong type, the rhetorical strategy for block is later said.
      • This is used in the. m file of B
if (_myblock) {_myblock (@ "1234567");    NSLog (@ "%@", str); }Description: If this is a block first judgment, the role is to determine whether the block has been allocated memory, if the definition is completed, and passed a string parameterif the block has a return value, then a value can be used to receive its return value, such as int num = _myblock (@ "1234567");
      • In the. m file of a
First IMPORTB the header file, and then create a B of the specific object is MYVC, and then myviewcontroller *MYVC = Segue.destinationviewcontroller;
Myvc.myblock = ^ (NSString *str) {NSLog (@ "%@", str);     }; Note: If the block has a return value, you need to add a return to the block. such as return 10, so that Myblock has a value, so that num in B has a value. That is, the value of the process is that the inner block has a value and then executes the external value.three. Block's circular reference problem1. Simple Circular ReferenceDescription of the circular reference: this should be released when the object does not want to be used, but because of the cyclic strong reference, no one can release who caused the memory leak. Where a block has a circular reference: The block in arc is a strong or copy property, the Self property of the current class is used inside the block, and the class contains the Block property of a class. Example: or the above example of the value of a, now if the. m file in a block in the use of Self.view.backgroundColor = [Uicolor Redcolor]; Now the reference relationship between these objects is as follows: So this creates a circular reference. Resolution of circular references within a block: In the following example, you can add a sentence outside a block (if you use typeof for an expression, the expression will not execute.) Only the type of the expression is given. ) __weak typeof (self) weakself = self, or it can __weak viewcontroller *weakself = self;2. Complex circular referencesThis has not been met, just see this used ... There's time to analyze this later!four. Block's memory analysis (ARC and non-arc verification)How to verify Arc or non-arc, a little bit of retrospective 1.arc cannot call retain and release, and the Dealloc method cannot call Super Dealloc. Non-arc Super Dealloc written on the last side 2. Project-Build The set method for Arcarc, settings, is as follows, with the previous value being unequal, releasing the old value, retain the new value: So we should try to use self in arc. This way, you call the Set method, not the underscore, because the memory leaks. Non-arc without weak, no strong, only corresponding assign and retainStrong and copy:Because the string above is used for copy, and the above code is what the arc does inside the copy, that is, it will release the old value, the new string name to copy a copy of the old _name. This will not affect the name when we change the _name. (PS: Under Arc generally if the string will not be changed as far as possible to use strong, because save copy, compared to copy more performance, for the use of block arc under the same, do not need copy to use strong just fine)Memory 5 AreaMemory is divided into 5 regions: heap, stack, method area, static zone (global zone), constant zonePS:The global and static zones are actually the same, and in memory, both global and static variables are stored in the static storage area, and the lifetime and the program are all allocated memory in the static data area. Reclaims memory after the program ends. They are scoped differently, the scope of the global variable is the entire project, the static global variable is the current program file, and the static local variable is the current function body.Heap: Manually managing MemoryStack: Once the code block is over, the system automatically reclaims the corresponding memory area first to understand block, Apple Official document block is the object. (because it is an object, so printing in%@ format can see its memory allocation area), the first sentence of the document description is as follows:

Under Non-arc:

1.situation of the global zone: Define a block as follows, and use it, and it will print as a global representation. The global zone indicates that it is available everywhere. (PS: If the block internal access static rhetoric outside the local variables, then it is also in the global zone, about the static zone and the global just above has been explained) 2.Stack Area: as follows when accessing an outside local variable A in the block, it prints the result, and the stack represents the stack areaSummaryAs follows: The memory allocation of a block is related to the variables it accesses internally, and if the access is a global variable, the block will be in the global zone; If a local variable is accessed, the block is assigned to the stack. (Nothing is accessed by default in the global zone) 3.Heap Area: When using copy for strong references, block will copy a copy to the heap area using retain rhetoric blocks in non-arc environments with a yellow warning, such as a warning tip it is best to use copy if you are using retain now, and a local variable A is accessed within the block ( This A is written on top of block, the code is as follows, then found a running program is Peng. (Bad memory access, error will appear when using self.) Block's place) This summary: In non-arc can not use retain reference block, because this will not put block in the heap, it will be in the stack area, so the code area out of parentheses will be destroyed, This will result in an error. If you use copy, you can put the block in the heap. So the block will not be destroyed.-So the block has to copy all the old programmers say, because there is no arc.under Arc:1.Global Zone: or the following code, the default block or the global zone, no access to the external variables are in the global zone, and whether arc-independent 2.Heap: When accessing an external local variable or object, the code is as follows, and it prints the result that this malloc allocated memory is represented on the heap. (This is a bit like arc. The default object is a strong reference, and the benefit is not to destroy it as soon as it is created.)Five. Transfer and change of the internal variables of blockLook at the code below, this is very simple, block print out must be 10Value PassingLook at the following code, this print is 5, although block () before the execution of a = 10, but because a = 5 immediately after being passed into the block, but has not been executed, that is, the memory is well-equipped. And then the block is the value of the transfer, then the outside changes cannot change the value inside. (if it is a pointer pass, you can)Pointer passingThen look at the following code, this print will be 10, the reason: As long as the local variable life cycle is the entire app running, then the pointer is passed here plus static, the life cycle with the entire program and survival. Same as the global zone (this is analyzed in block memory analysis) Under the condition is also the pointer pass, so print out will also be the ten block variable passSummary: If a local variable is accessed inside the block, then the value is passed, or the pointer is passed

A simple summary of block usage

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.