iOS multi-thread block programming

Source: Internet
Author: User
Tags gcd

1 What is blockBeginning with IOS SDK 4.0, Apple introduced the block feature. Block is literally a block of code. But it's wonderful to be able to pass a number of parameters when inline (which is very much like C + +) runs.

At the same time, the block itself can be passed as a parameter between methods and functions. This gives the block an infinite possibility.

For closures (blocks), there are very many definitions. The closure is a function that can read the internal variables of other functions, which is close to the nature and better understood.

For the first contact with the block of the classmate, will think some around, because we are accustomed to write this program main () {Funa ();} Funa () {Funb ();} Funb () {...}; Is the function main called function A, function A called function B ... Functions run sequentially, but not all in reality. For example, Project manager M., who had 3 programs ape A, B, C, when he gave the program ape A to arrange for functional F1, he did not wait for a to finish. To arrange B to implement F2, but to arrange for a function F1,b function F2,c function F3, and then may write technical documents, and when a encounter problems, he will come to project manager m, when B is done, will inform M. This is an example of an asynchronous run. In this case, block will be able to do the job, because in the project manager m, to a work arrangement. At the same time will tell a if you encounter difficulties, how to find him to report problems (such as phone number). This is the project manager m to a callback interface, the operation to be back off. For example, after receiving the telephone, Baidu inquires back to the Web page content to a. This is a block, when M confessed to work. has been defined well. The task number of the F1 (local variable) is obtained, but it is called when a problem is encountered, the cross function is queried by the project manager m for Baidu, and the block is recalled after the result.

Block is a special OC object that is built on the stack, not on the heap, so one is for performance and the other is to make it easy to access local variables. By default, local variables used by the block are copied, not reserved. So it can't change the value of a local variable. Suppose you add __ to a variable block, then the compiler will not copy the variable, but to find the address of the variable, through the address to access variables, in fact, directly manipulate variables. The other block is allocated on the stack, so once you leave the scope, it will be released, so let's say you want to use it somewhere else, A copy must be copied. So you need to use copy: @property (nonatomic, copy) void (^ontextentered) (NSString *enteredtext) When the property definition is fast, and the block is not preserved. Retain doesn't make sense to blocks. 2 Block Implementation Principle objective-c is the extension of the C language, the implementation of block is based on pointers and function pointers. From the development of computational language, the earliest goto, the pointer to the high-level language, to the object-oriented language block, from the machine's thinking, step closer to human thinking, in order to facilitate the developer more efficient, direct description of the logic of Reality (demand). Research on block implementation in iOS talk about the implementation of Objective-c Block 3 Block's use of block using instance A:cocoatouch frame animation effect is one of the important features of the iOS interface. Caanimation is the abstract parent class for all animated objects. As a newcomer, use more of the animation method under UIView (class method).

There are several ways to use animations under UIView.

Method One: Set Beginanimations Memberview for the need to join the view of the sub-view, Mivc.view as a sub-view, in use, the need to replace these two places to be aware of. Be sure to use [UIView commitanimations]; the animation will take effect through [UIView setanimationduration:1]; Set the duration.

Method Two: After IOS4.0, we have a new method, + (void) Transitionwithview: (UIView *) View Duration: (nstimeinterval) Duration options: ( uiviewanimationoptions) options animations: (void (^) (void)) animations completion: (void (^) (BOOL finished)) completion , it is still the UIView class method, but the block object is used. A block object is a set of instructions that can be passed (like a variable) and can be thought of as a function pointer of C.

 [uiview transitionwithview:self.view                      &NB Sp   duration:0.2                         option  ------ s:uiviewanimationoptiontransitionflipfromleft                        animations:^{[Self.view AddSubview:yellowView.view];}                         completion:null];  b:  make declare blocktypedef void (^didfinishblock) with typed (NSObject *ob); This declares a block of type Didfinishblock, then @property (nonatomic, copy) Didfinishblock  finishBlock; declare a block object, note that the object property is set to copy, and when you receive a block, you will be actively copying one copy.  __block is a special type. The local variable declared with the keyword can be changed by the block, and its value in the original function will be changed. C:1 What are the advantages of using block and using delegate to complete the trust model?  block different variables because it is not a single variable, but a method,  we are going to pass a block of code, and this code block can exist in the argument,  this argument is not given when the block is defined by the value, Instead, we give the value .   when we actually execute the block, so for the number of referencesblock, when we pass the past, it needs the receiver to provide the corresponding parameters of the ability to execute,   so we can do the merit of the Class A for the future events of Class B, even if we don't have the detailed arguments of these events .  In a sense it would not be necessary to entrust the relationship between the two .  the trust relationship is a Class B after an event, notify Category A, let Class A again for this event to do some processing    and use block, then a has been in advance to the event of the processing method told Class B, When the time comes, Class B does not need to notify Class A, and the implementation of the set-up processing method (block) can be .   assuming that you are executing a method and want to tell the method how you want to do it in a particular situation, you can use block.  &NBSP;&NBSP;D:&NBSP;GCD:&NBSP;GCD mainly use blocks to replace the trust mode, so that the program becomes concise, the same time execution efficiency is improved .    copy code     static int clicknum = 0;    self. Mylabel = [[UILabel alloc]init];    while (Clicknum <20) {        Dispatch_async (Dispatch _get_main_queue (), ^{            self. MyLabel.Text = [NSString stringwithformat:@ "%d", clicknum++];//ui drawing must be in the main thread        });        [Nsthread sleepfortimeinterval:1];   } Copy code about block and GCD programming can refer to this article:  and this article     arc and non-arc block differences: &NBSP;ARC when the block will be copied from the stack itself to push, and __block and __weak use problems   because the block is built on the stack by default, soAssuming that you leave the method scope, the block will be discarded, in the non-ARC case, we have to return a block, need [Block copy], under the ARC, in the following cases, the block will voluntarily be copied from the stack to the heap: 1. is run Copy Method 2. Returns a value of 3 as a method. Assign a block to a value attached to __ The strong modifier of the ID type of the class or Blcok type member variable is 4. When the method name contains a Usingblock cocoa framework method or is passed in the GDC API. For non-arc, to prevent circular referencing, we use __ Block to modify the objects that are useful in the BLOCK: __block ID blockself=self;self.blk=^{nslog (@ "%@", blockself),  //object on the stack under non-arc, The block does not copy it, only uses it, and does not add a reference count.}; For arc, to prevent circular referencing, we use __weak to decorate objects that are useful in block: __weak ID weakself=self;self.blk=^{nslog (@ "%@", weakself);}; Assuming that under ARC, in order to prevent circular references, using __block to decorate the objects that are useful in the block will still be retain, so you need to do more settings __block ID blockself=self;self.blk=^{nslog (@ "%@" , blockself); self.blk=nil;  //BLK was released, BLK only Blockself was released};blk ();  //and must be executed once, otherwise cannot be released this makes the blk disconnected from the blockself. So many advantages are the ability to control the holding time of self. Just in the latest iOS version number, these will always be indicated by an exclamation mark in the form of a circular reference issue.   Such writing methods are not recommended. Unless you want to change the __block pointer in the block. In fact, we use the __weak modifier, just can't change the object itself, but can change the object's properties . 

iOS multi-thread block programming

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.