Objective-c Block in iOS in 4.0 version of the use
Block is the new program syntax for iOS after version 4.0.
After iOS SDK 4.0, block appears in almost all new versions of the API, in other words, if you do not understand the concept of block is not able to use the new version of SDK 4.0, so although the syntax of the block itself is a bit difficult, But in order to use the new features of iOS we have to bite the bullet to understand the new program concept.
First, take a look at what is block
We use the ' ^ ' operator to declare a block variable, and after declaring a block variable, it is like declaring a normal variable, and finally adding '; '.
Next, we use an example to declare a simple block variable.
Int (^block) (int) = NULL;
Let's take a look at the syntax for declaring a block variable
Data return value type (^ variable name ) (parameter list) = NULL;
Next, we assign a value to the block variable just now.
block = ^ (int m) {return m * m;};
And then we'll use the block variable once.
By using the block variable, the square of the integer constant 10 is computed and printed on the controller output NSLog (@ "10 squared is:%d", block (10));
Note that by now we should have found the use steps of the block variable, there are steps similar to the function
-
The first is to declare (declare the function, declare the block variable);
-
It is then implemented (implementing the function, assigning the value of the block variable to the implementation process);
-
The final call is required to achieve the specific function
Second, take a look at how to directly use the block parameter
Array sorting
//declaring an array variable nsmutablearray *mutablearray = [[ nsmutablearray alloc] initwithobjects:@ "5", @ "2", @ "3", @ "9", @ "7", nil]; //the array in ascending order using block directly [mutablearray sortusingcomparator:^ Nscomparisonresult (ID OBJ1, ID OBJ2) { // An object that converts two arguments to a string NSString *value1 = (nsstring *) obj1; nsstring *value2 = (NSString *) obj2; // The results of the comparison between Value1 and value2 two objects return directly to return [value1 compare: value2]; }]; //printing variable array variables nslog (@ "%@", Mutablearray);
A Simple network asynchronous request
//declaring network Address objects NSURL *url = [NSURL urlwithstring:@ "http://www.qq.com"]; //according to network address object, declare network Request object NSURLRequest *request = [NSURLRequest requestWithURL:url]; //directly using the block variable to complete the data return function after successful link [NSURLConnection sendasynchronousrequest:request queue:[nsoperationqueue mainqueue] completionhandler:^ ( Nsurlresponse *response, nsdata *data, nserror *connectionerror) { //converting binary data to string objects using UTF8 encoding Nsstring *result = [[nsstring alloc] initwithdata:data encoding: nsutf8stringencoding]; //results after the print link is complete &nbsP; nslog (@ "%@", result); }];
You can see that many of the features in the iOS platform have been integrated with the block syntax approach.
Third, take a look at the block syntax in-depth understanding
In this section, the main thing to introduce is the use of __block modified variables to accomplish the function.
Let's look at an example first.
Declares a local integer variable int intvalue = 3; DECLARE a block variable int (^block) (int) = ^ (int m) {return m * intvalue) with a return value of int, an int parameter; }; Call the block variable, 5 as the result of the parameter NSLog (@ "block (5) =%d", block (5));
In the example above, we refer to the Intvalue variable as an external variable during block execution, which can be used directly during block execution.
Let's look at an example.
Declares a local integer variable int intvalue = 3; Declares a block variable int (^block) (int) = ^ (int m) {intvalue++) that returns a value of int, an int parameter; return m * intvalue; }; Call the block variable, 5 as the result of the parameter NSLog (@ "block (5) =%d", block (5));
In the example above, we compile the program and find that the compiler has a red error , and the error message is
Variable is not assignable (missing __block type specifier)
Why is there an error message that cannot be assigned?
When the block is implemented, it makes a read-only copy of the stack variable defined in the method it refers to, and then uses that read-only copy within the block blocks.
To avoid the above error, use the __block modifier to modify the external variable to inform the compiler that the external variable intvalue and the Intvalue in the block refer to the same memory address, without the need for a memory copy. The following example
The Intvalue local integer variable is decorated with the __block modifier __block int intvalue = 3; Declares a block variable int (^block) (int) = ^ (int m) {intvalue++) that returns a value of int, an int parameter; return m * intvalue; }; Call the block variable, 5 as the result of the parameter NSLog (@ "block (5) =%d", block (5));
Iv. memory issues to be aware of using block
Use Weak–strong Dance technology to avoid circular references
Examples are as follows
viewcontroller.m//// created by lewis.//#import "ViewController.h" @ interface viewcontroller () @[email protected] viewcontroller{ id observer;} - (void) viewdidload{ [super viewdidload]; //add an observer, observe the subject to modify the message notification, and after receiving a message notification, print the View Controller object observer = [[ nsnotificationcenter defaultcenter] addobserverforname:@ "Kthemechangenotification" object:nil queue:[nsoperationqueue mainqueue] usingblock:^ (nsnotification *note) { nslog (@ "%@", self); }];} - (void) didreceivememorywarning{ [super didreceivememorywarning]; // dispose of any resources that can be recreated.} When the view controller object is destroyed, remove observer- (void) DEALLOC{ &Nbsp; if (Observer) { [[ nsnotificationcenter defaultcenter] removeobserver:observer]; }} @end
In the code above, we add an observer to the notification hub and then release the registration at Dealloc, and everything looks normal. But here are two questions:
-
In the message notification block refers to self, where the Self object is block retain, and Observer retain a copy of the block, Notification Center and hold observer. So as long as the Observer object has not been de-registered, the block will be held by the Notification center, so that self will not be freed and its dealloc will not be invoked. And we expect to removeobserver in Dealloc to remove the notification center from the Observer/block retain.
-
At the same time, observer is defined as an assignment in the Self's class, so it is retain by self, thus forming a circular reference.
The solution is as follows.
viewcontroller.m//// created by lewis.//#import "ViewController.h" @ interface viewcontroller () @[email protected] viewcontroller{ id observer;} - (void) viewdidload{ [super viewdidload]; //first declare a weak weak object __weak ViewController *wSelf = self;         //add observer, watch topic Modify message notification, and after receiving a message notification, print the View Controller object observer = [[nsnotificationcenter defaultcenter] addobserverforname:@ " Kthemechangenotification " object:nil queue:[nsoperationqueue mainqueue] usingblock:^ ( Nsnotification *note) { //use strong objects to reference weak objects during block execution viewcontroller *bself = wself; if (bself) { nslog (@ "%@", bself); } }];} - (void) didreceivememorywarning{ [super didreceivememorywarning]; // dispose of any resources that can be recreated.} When the view controller object is destroyed, remove observer- (void) dealloc{ if (Observer) { [[NSNotificationCenter defaultCenter] removeObserver:observer]; }} @end
First, a weak reference to self is defined before the block wself, because it is a weak reference, so wself becomes nil when Self is freed, and then references the weak application in the block, considering the multithreaded case, by using a strong reference bself to reference the weak reference, as If self is not nil, self is retain to prevent self from being freed during subsequent use, and the strong reference sself is then used in subsequent block blocks, noting that the bself is nil-detected before use because a weak reference to wSe in a multithreaded environment LF The bself is assigned a strong reference, the weak reference wself may already be nil.
With this Weak-strong technique, the block does not hold a reference to self, thus breaking the circular reference.
Objective-c Block in iOS in 4.0 version of the use