Use of Block in OC

Source: Internet
Author: User

Use of Block in OC

1. Block Definition

1.1 Definition

(1) Block is a data type in OC and is widely used in iOS development.

(2) ^ is the unique identifier of a Block.

(3) The Block implementation code is included {}.

(4) In most cases, the inline function is defined and used.

(5) Block is similar to function pointers in C, but it is more flexible to use.

1.2 sample code

void(^demoBlock)() =^ {   NSLog(@"demo");};int(^addBlock)(int, int) =^(int x, int y) {   return x +y;};

Note: (1) (return type) (^ block name) (parameter type) = ^ (parameter list) {Code Implementation}; (2) if no parameter exists, the () parameter list after the equal sign can be omitted


II. Block usage

2.1 Block is directly transmitted as a parameter

NSArray * array = @ [@ "Zhang San", @ "Li Si", @ "Wang Wu", @ "Zhao Liu"]; [array enumerateObjectsUsingBlock: ^ (id obj, NSUIntegeridx, BOOL * stop) {NSLog (@ "the content of item % d is % @", (int) idx, obj); if ([@ "" isEqualToString: obj]) {* stop = YES ;}}];


Description: traverses and NSLog () content in the array. When obj is "Wang Wu", the traversal is stopped.
2.2 Method for passing objects into a Block

NSString * stopName = @ "Wang Wu"; NSArray * array = @ [@ "Zhang San", @ "Li Si", @ "Wang Wu", @ "Zhao Liu"]; [array enumerateObjectsUsingBlock: ^ (idobj, NSUInteger idx, BOOL * stop) {NSLog (@ "the content of item % d is % @", (int) idx, obj ); if ([stopName isEqualToString: obj] | idx = stopIndex) {* stop = YES ;}}];


Note: to ensure the normal operation of the Code in the Block, when the stopName pointer is passed to the Block, the Block automatically references the stopName pointer.

2.3 When a Block uses local variables as parameters, the Block can also use the local variables declared before definition.

IntstopIndex = 1; NSArray * array = @ [@ "Zhang San", @ "Li Si", @ "Wang Wu", @ "Zhao Liu"]; [arrayenumerateObjectsUsingBlock: ^ (id obj, NSUInteger idx, BOOL * stop) {NSLog (@ "% d content is % @", (int) idx, obj); if ([@ "" isEqualToString: obj] | idx = stopIndex) {* stop = YES ;}}];

Note: by default, variables outside the Block are read-only in the Block!

BOOL flag = NO; [arrayenumerateObjectsUsingBlock: ^ (id obj, NSUInteger idx, BOOL * stop) {if ([@ "" isEqualToString: obj] | idx = stopIndex) {* stop = YES; flag = YES; // compilation Error !!! }];

If you want to modify a local variable other than the Block, you need to use the _ block keyword!

_ Block BOOL flag = NO; [arrayenumerateObjectsUsingBlock: ^ (id obj, NSUInteger idx, BOOL * stop) {if ([@ "" isEqualToString: obj] | idx = stopIndex) {* stop = YES; flag = YES; // you can modify it now !!! }];


You do not need to use the _ block keyword. In the block code, you can modify the value of the member variable (rarely used)

2.4 use typedef to define a Block use typedef to define the type of a Block, which is easy to use directly in the future

typedef double(^MyBlock)(double, double);MyBlock area = ^(double x, double y) {    return x * y;};MyBlock sum = ^(double a, double b) {    return a + b;};NSLog(@"%.2f", area(10.0, 20.0));NSLog(@"%.2f", sum(10.0, 20.0));


Note: (1) typedef is a keyword used to define the type, and MyBlock is the defined Block type (2) area and sum are two Block variables of the MyBlock type (3) Although, typedef can simplify the definition of a Block, but the typedef keyword is not frequently used in actual development. This is because the Block has great flexibility, especially when passing parameters, block is used for immediate use.

2.5 adding a Block to an array is a data type. You can use a Block as a special object.

# Pragma mark is defined and added to the array @ property (nonatomic, strong) NSMutableArray * myBlocks; int (^ sum) (int, int) = ^ (int x, int y) {return [self sum: x y: y] ;}; [self. myBlocks addObject: sum]; int (^ area) (int, int) = ^ (int x, int y) {return [self area: x y: y];}; [self. myBlocks addObject: area]; # Call the Blockint (^ func) (int, int) = self. myBlocks [index]; return func (x, y );



2.6 Block loop reference
Directly run the Code:

@ Property (nonatomic, strong) NSMutableArray * myBlocks; # pragma mark changes the code to call the self method int (^ sum) (int, int) = ^ (int x, int y) {return [self sum: x y: y] ;}; [self. myBlocks addObject: sum]; # called automatically when the pragma mark object is released-(void) dealloc {NSLog (@ "DemoObj released ");}
Note:

The error in the above Code indicates that the object cannot be released as a result of loop reference!

(1) self's strong reference to myBlocks

(2) strong reference of sum to self

(3) when an object is added to an array, it will be strongly referenced by the array.


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + records + 1rK/seTBv8SsyM + 2vMrHx7/S/records + records/J0tS9q77Wsr + x5MG/records = "brush: java;" >__ weak DemoObj * weakSelf = self;

When weakSelf is referenced in a Block, the Block will no longer make a strong reference to self.

int(^sum)(int, int) = ^(int x, int y) {    return [weakSelf sum:x y:y];};


2.7 Use Cases of Block in iOS

(1) traverse arrays or dictionaries
(2) view animation
(3) sorting
(4) Notification
(5) handle errors

(6) multithreading...



























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.