Blocks learning notes Summary

Source: Internet
Author: User

This article is a summary of Apple's "Blocks Progromming Gude" study notes.

Class C syntax and runtime characteristics of objects. Similar to Standard C functions, but in addition to executable code, it may also contain variable auto binding (stack) or memory hosting (HEAP ). Therefore, a block maintains a state set (data), which can be used to affect program behavior during execution. Block is particularly useful for callback.

You can use Blocks in mac OS 10.6 and later versions, IOS 4.0 and later versions.

Blocks is open-source and can be found in LLVM's compiler-rt subproject repository (a subproject of LLVM's RT compiler.

1. Declare a Block

1 int (^ myBlock) (int) = ^ (int num) {2 return num * num; 3} 4 Description: 5 int: return value type, if no value is returned, it is void6 (^ myBlock). The block definition requires a ^ mark. myBlock is the block name 7 (int): List of parameter types, if no parameter exists, it is void8 ^ (int num): list of parameters starting with ^. If no parameter exists, it is void. You can also omit 9 {}: block Body (equivalent to the function body)

2. Use block

1 printf("%d",myBlock(7));

3. In many cases, you do not need to live the block, but directly use the inline block.

1 char *myCharacters[3] = {"TomJohn","George","Jim Green"};2 3 qsort_b(myCharacters,3,sizeof(char *),^(const void *l,const void *r){4     char *left = *(char **)l;5     char *right = *(char **)r;6     return strncmp(left,right,l);7 });

4. There are some methods in Cocoa frameworks that use block as parameters. Generally, they are used as Callback when the operation is completed, instead of performing operations on a set of objects. The example shows how to use the NSArray sortedArrayUsingComparator: block.

1-(void) sort {2 NSArray * stringArray = [NSArray arrayWithObjects: @ "Java Network Programming", @ "Java development practices", @ "grinding design mode ", @ "iPhone development tips", @ "start-up Web Crawler writing", @ "Cocos2d game development practices", @ "Oracle ", @ "Java Web development practices ", nil]; 3 static NSStringCompareOptions options = random | 4 NSNumericSearch | 5 bytes | 6 NSForcedOrderingSearch; 7 NSLocale * currentLocale = [NSLocale currentLocale]; 8 NSComparator sortBlock = ^ (id string1, id string2) {9 nsange string1Range = NSMakeRange (0, [string1 length]); 10 return [string1 compare: string2 options: options range: string1Range locale: currentLocale]; 11 }; 12 NSArray * sortedArray = [stringArray sortedArrayUsingComparator: sortBlock]; 13 NSLog (@ "array: % @", sortedArray); 14}

5. Blocks variables in the same scope cannot be modified by default. However, if the _ block keyword is used to modify the variables in the same scope, blocks can be used to modify the variables.

6. A block is an anonymous collection of Inline code:

    * The parameter type is the same as that of a function.
    * Types of returned values with inferences and declarations
    * It can capture the state of the same scope where its declaration is located, and share changes with other bolcks whose definitions are in the same scope.
    * Continuously share and change the status of the same scope after the same scope is destroyed

7. Blocks generally represents a small, self-contained code segment. Therefore, they are used as encapsulated work units for concurrent execution, a set item, or callback when other operations are completed.

Blocks is a practical alternative to traditional callback functions for the following two reasons:

They allow you to write code at the place you call to implement the operations to be executed later. Therefore, Blocks is usually used as a parameter of the Frameworks method.

They allow you to access local variables, instead of using a data structure that inherits all context information when you want to perform operations for callback. You can directly access local variables.

8. blocks is similar to a function pointer, except using ^ instead *. The following are valid block declarations:

1 void (^ blockReturningVoidWithVoidArgument) (void); 2 int (^ blockReturningIntWIthIntndCharArguments) (int, char); 3 void (^ forward [10]) (int ); 4 5 Blocks also supports variable parameters (...). A block without any parameters must be marked with void in the parameter list.

9. A bolcks can be forcibly converted to any type, and vice versa. However, a block cannot be referenced using the * modifier, therefore, a block may not be computed during compilation. You can also create block types. This is generally considered the best method when block with the same given signature is used in multiple places:

1 typedef float (^MyBlockType) (float,float);2 MyBlockType myFirstBlock = ...;3 MyBlockType mySecondBlock = ...;

10. Create a Block

1 int (^ oneFrom) (int); 2 oneFrom = ^ (int anInt) {3 return anInt-1; 4 }; 5. If you explicitly declare a return value to a block expression, it will automatically infer from the block content. If the returned value is inferred and the parameter list is also void, you can also omit the void of the parameter list. If there are multiple return statuses, they must be exactly matched (if necessary, use forced type conversion)

11. Global Blocks

At the file level, block can be used as a global identifier:

1 #import <stdio.h>2 3 int GlobalInt  = 0;4 int (^getGaobalInt)(void) = ^{return GlobalInt;};

12. In the block entity code, variables can be processed in five ways. Three standard types of variables can be referenced, just as in a function:

Global variables: including static local variables

Global function: Technically speaking, this is not a variable.

Partial variables and parameters within the Closed range

* The function is a _ block variable. These are variable in the block, and any referenced block is saved as a copy to the heap.

* Reference const

* In the implementation method, blocks may reference the Objective-C instance variable.

Variables used in Blocks follow the following rules:

Global variables are accessible, including static variables in the same scope

The parameters passed to the block can be accessed (the same as the function parameters)

The heap variables within the same scope in the program are used as the const variables (read-only ). Their values are used in the block expression in the program. In a nested block, this value is captured within the nearest closed range.

Variables that belong to the same scope and are identified by the _ block modifier are passed as references, so they are variable.

The block variables within the same scope are the same as the local variable operations of the function.

Example: Use a local non-static variable

1 int multipiler = 7; 2 int (^ myBlock) (int) = ^ (int num) {3 return multipiler * 7; 4 }; 5. If you modify the multipiler value in the block body, an error will occur.

13. You can use the _ block modifier to specify that the introduced variables can be changed. Such variables are stored within the scope of shared variables, all blocks and block copies are declared or created within the same scope as the variables. You can specify to introduce a variable that can be changed, that is, read-write, by applying the _ block storage type modifier. The _ block Storage of local variables is similar to the storage types such as register, auto, and static, but they are not compatible. _ Block variables are stored in the scope of shared variables. All blocks and block copies are declared or created in the same scope as the variables. Therefore, if any blocks copy statement does not exceed the end of the stack, the storage will save the stack frame from being destroyed (for example, encapsulated as executed later ). Multiple blocks in the same scope can use one shared variable at the same time. As an optimization, block is stored on the stack, just like blocks itself. If Block_copy is used to copy a copy of the block (or a copy message is sent to the block in Objective-C), the variable is copied to the heap. Therefore, the address of a _ block variable can be changed over time.

Variables using _ block have two restrictions: they cannot be variable-length arrays, and they cannot be data structures that contain arrays with C99 variable lengths.

 

1 __block int x = 123; // x lives in block storage2 void (^printXAndY)(int) = ^(int y) {3 x = x + y;4 printf("%d %d\n", x, y);5 };6 printXAndY(456);
1 The following example shows the interaction between blocks and several other types of variables: 2 extern NSInteger CounterGlobal; 3 static NSInteger CounterStatic; 4 {5 NSInteger localCounter = 42; 6 _ block char localCharacter; 7 void (^ aBlock) (void) = ^ (void) {8 ++ CounterGlobal; 9 ++ CounterStatic; 10 CounterGlobal = localCounter; // localCounter fixed at block creation11 localCharacter = 'a'; // sets localCharacter in enclosing scope12}; 13 ++ localCounter; // unseen by the block14 localCharacter = 'B '; 15 aBlock (); // execute the block16 17 // localCharacter now 'A' 18}

14. In the reference counting environment, by default, When you reference an Objective-C object in the block, the object will be retain. When you reference an instance variable of an object, it is also retain. But the object variables marked by the _ block storage type modifier will not be retain

Note: In the garbage collection mechanism, if you use _ weak and _ block to identify a variable at the same time, the block will not guarantee its validity. If you use block during implementation, the memory management rules of objects are more subtle:

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.