Objective
The ios4.0 system has started to support block, and during programming the block is considered an object by Obj-c, which encapsulates a piece of code that can be executed at any time. A block can be used as a function parameter or as a return value for a function, and it can have either an input parameter or a return value. It is similar to a traditional function pointer, but differs: The block is inline, and it is read-only to local variables.
Block and Function Similarity: (1) can save Code (2) has a return value (3) The physical parameter (4) is called the same way.
Use of block
1. Definition of block
Declarations and implementations are written together, just as the declaration of a variable implements int a = 10;
Int (^ablock) (int,int) = ^ (intnum1,intnum2) {
RETURNNUM1 * NUM2;
};
Declarations and implementations are separated, as if the variables were first declared after the implementation of int a;a = 10;
Int (^cblock) (int,int);
Cblock = ^ (intnum1,intnum2)
{
RETURNNUM1 * NUM2;
};
It defines a blocks object named Ablock and carries the relevant information:
1, Ablock has two formal parameters, respectively, the type of int;
2, the return value of ablock is int type;
3, the right side of the equation is the concrete realization of blocks;
4, ^ with edge blocks declaration and implementation of the logo (keywords);
Of course, you can define other forms of block. E.g: no return value, no formal parameters, etc.;
void (^bblock) () = ^ ()
{
INTA = 10;
printf (num =%d,a);
};
2. Blocks access rights
Blocks can access local variables, but cannot be modified.
INTA = 10;
Int (^dblock) (int) = ^ (Intnum)
{
A++;//not work!
Returnnum * A;
};
The reason why cannot be modified here is determined during compilation, when the compiler compiles the value of a to block as a new variable (assuming a ' = 10), at which point a ' and a are not related.
This is where the value in the function is passed. Add keyword If you want to modify: __block or static
__blockinta = 7;
Int (^dblock) (int) = ^ (Intnum)
{
a++;//work!
Returnnum * A;
};
3. Call of block
Block calls are just like calling functions. e.g:
1INTC = Ablock (10,10);
Bblock ();
4. Block application
Suppose we are familiar with the proxy recursion value, we may love and hate the agent! Let's start with the Model a page push
b page, if the value of a page is passed to page B, attributes and single-pass values can be done! But if the pop process to pass the value of the B page to a page, then you can use a single case or agent! Speaking of agents,
We must first declare the agreement, create the agent, it is very troublesome. Often we pass a value that requires a lot of code to be written between two pages, which changes the overall order of the pages and the readability is discounted. Therefore, this
, block is an optimization solution!
5, block of memory management
Block itself is like an object can be retain, and release. However, when the block is created, its memory is allocated on the stack (stack), not on the heap (heap). His own domain is the scope at the time of creation, and once it is created, calling block will cause the program to crash. Like the example below. I created a block in view did load:
-(void) viewdidload
{
[Superviewdidload];
int number = 1;
_block = ^ () {
NSLog (@number%d, number);
};
}
And this block is called in the event of a button:
-(Ibaction) Testdidclick: (ID) Sender {
_block ();
}
At this point I press the button will cause the program crashes, the solution to this problem is to create a block after the need to call the Copy method. Copy will move the block from the stack to the heap, then you can use the block in other places ~ Modify the code as follows:
_block = ^ () {
NSLog (@number%d, number);
};
_block = [_blockcopy];
In the same way, it is important to note that when the block is placed in the collection class, if the generated block is placed directly into the collection class, it is not possible to use the block elsewhere, you must copy the block. But the code looks relatively odd:
[Array addobject:[[^{
NSLog (@hello!);
} copy] [autorelease]];
6. Circular Reference
For non-arc, to prevent circular referencing, we use __block to decorate the objects used in the block:
For arc, to prevent circular referencing, we use __weak to decorate the objects used in the block. The principle is: in Arc, if the __strong modifier's automatic variable is referenced in the block, it is equivalent to the block's reference count of that variable +1.
This is actually a small derivative in the 1th. When using member variables within a block, such as
@interface Viewcontroller:uiviewcontroller
{
NSString *_string;
}
@end
In block creation:
_block = ^ () {
NSLog (@string%@, _string);
};
The _string here is the equivalent of self->_string;, so block is a retain to the internal object. In other words, self will be retain once. When Self is released, it is necessary to release the self after the block is released, but the block's release needs to wait for Self's dealloc to be released. As a result, a circular reference is formed, causing a memory leak.
The modification scenario is to create a new local variable for the __block scope and assign self to it, and the local variable is used inside the block to take the value. Because the __block tag variable is not automatically retain.
__block Viewcontroller *controller = self;
_block = ^ () {
NSLog (@string%@, controller->_string);
};
Bloggers browsed a lot of blogs, summed up, block is actually (bottom C + +): Pointer to the struct, the bottom layer will create a struct, implement the construction method, to connect parameters, the compiler will generate the block's internal code corresponding function.
Block Combat: Use block to transfer values between pages
There are many places to use blocks, where the value is just a small part of it, and the following is a description of the value of block between two interfaces:
Let's talk about thought:
First, create two view controllers, create a Uilabel and a uibutton in the first view controller, where Uilabel is to display the string passed by the second view controller, UIButton is to push to the second interface.
The second interface has only one Uitextfield, is to enter the text, when the input text, and return to the first interface, when the second view is going to disappear, the second interface on the textfiled text to the first interface, and displayed on the Uilabel.
In fact, the core code on a few lines of code:
Here's the main code: (Because I'm a project created with storyboard, so the above properties and the corresponding method are using the system-generated outlet)
One, declare the Block property in the. h file of the second view controller
typedef void (^returntextblock) (NSString *showtext);
@interface Textfieldviewcontroller:uiviewcontroller
@property (nonatomic, copy) Returntextblock Returntextblock;
-(void) Returntext: (returntextblock) block;
@end
The first line of code is to redefine a name for the block to be declared.
Returntextblock
In this way, the following will be very convenient when used.
The third line is a block property defined
Line four is a function that passes in a block statement in the first interface, but it doesn't have to be, but plus it reduces the amount of code written.
Ii. methods for implementing the second view controller
-(void) Returntext: (returntextblock) Block {
Self.returntextblock = Block;
}
-(void) Viewwilldisappear: (BOOL) Animated {
if (self.returntextblock! = nil) {
Self.returntextblock (Self.inputTF.text);
}
}
Where Inputtf is the Uitextfield in the view.
The first method is to define the method, save the incoming block statement block to this class instance variable Returntextblock (. h defined in the attribute), and then look for a timing call, and this time is said above, when the view will disappear, need to rewrite:
-(void) Viewwilldisappear: (BOOL) animated;
Method.
Third, get the second view controller in the first view, and invoke the defined property with the second view controller
Write in the following ways:
-(void) Prepareforsegue: (Uistoryboardsegue *) Segue Sender: (ID) sender
{
Get The new view controller using [Segue Destinationviewcontroller].
Pass the selected object to the new view controller.
Textfieldviewcontroller *TFVC = Segue.destinationviewcontroller;
[TfVC returntext:^ (NSString *showtext) {
Self.showLabel.text = Showtext;
}];
}
Uncover the mystery of block
Suppose a has a task, is to go to the warehouse to take a piece of A4 paper into the conference room, and then write a plan on the paper. Take the paper and go through the warehouse manager, so a notify the warehouse administrator to come over the paper. Since the administrator is an old
The head movement is very slow, moreover a also has other work, if waits for the administrator to be too wasted the time, the reasonable method is lets the warehouse administrator carry on the paper the work, a notifies the administrator to continue own work. A
I do not know when the warehouse manager can finish the paper, also do not know when you can write a proposal on paper. This is where the block mechanism comes in handy, using a mechanism that allows a to notify the warehouse administrator
Take the paper at the same time, tell the warehouse administrator to put the paper into the number XX conference room, and arrange to write on the paper planning content, when the administrator took the paper, it may be a while later will have an assistant to write the plan content on paper.
We'll map this story to the code:
#pragma mark-third-party login
-(void) btnloginweiboclicked: (ID) Sender {
[_waitcirclestartanimating];
[[hsloginclasscreateinstance]loginwithplatformtype:sharetypesinaweibowithblock:^ (BOOLsuccess,idmessage) {
if (success) {
Jump out of the login page
[selfdismissviewcontrolleranimated:yescompletion:^{}];
[_waitcirclestopanimating];
NSLog (@ "Sina Weibo%@", message);
}else{
}
}];
Test statistics
Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default,0), ^{
nsdate* date = [Nsdatedate];
Nstimeinterval nowtime = [datetimeIntervalSince1970];
nsstring* netstatus = (nsstring*) [[Nsuserdefaultsstandarduserdefaults]objectforkey:netstatus];
[[Hsstatisticsmodulestatisticsmodule]makesession:nowtime:oper_in: @ "Noid"];
[[Hsstatisticsmodulestatisticsmodule]uploaddata:netstatus: [nsstringstringwithformat:@ "%f", NowTime]];
});
}
Please look at this code, the whole method is a to do the work, Startanimating/loginwithplatformtype/dispatch_async is a to do the three tasks, Since Loginwithplatformtype takes a while to complete, and the loginwithplatformtype is done according to the results, we handle the loginwithplatformtype asynchronously. The block code snippet is the operation H to be done after Loginwithplatformtype gets the result, and the block notation here indicates that we set the operation H first and then continue with the other work. When Loginwithplatformtype executes OK, someone (probably the assistant) will be able to perform the operation H.
The block for iOS interview
1 What is block
For closures (block),
There are many definitions in which closures are functions that can read the internal variables of other functions, which are close to nature and better understood. For the first contact with the block of the students, will feel a bit around, because we are accustomed to write this
The kind of program main () {Funa ();} Funa () {Funb ();} Funb () {...};
Is the function main called function A, function A called function B ...
The functions are executed sequentially, but not in reality, such as project manager M, who has 3 programmers a, B, and C, and when he arranges for programmer A to implement functional F1, he does not wait for a to finish, and then
To arrange B to implement F2, but to arrange for a function F1,b function F2,c function F3, 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 asynchronous execution. In this case, block will be able to do the job, because in the project manager m, for a work, and will also tell a if encounter difficulties, how to find his report
Problem (such as hitting his cell phone number), this is the project manager m to a callback interface, to return the operation, such as receiving the phone, Baidu query, back to the Web content to a, this is a block, in M
Confessed to work, has been defined, and obtained the F1 task number (local variable), but when a encountered a problem, only call execution, cross-function in the project manager m query Baidu, get results after the callback
Block
2 Block Implementation principle
Objective-c is an extension of the C language, and 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, a step closer to human thinking, in order to facilitate developers more efficient, direct description of the logic of Reality (demand).
Here are two great posts to introduce block implementations
Probe into block implementation in iOS
On the realization of Objective-c block
3 Use of block
Working with instances
Block invocation of animation effect under Cocoatouch frame
Use typed to declare block
typedef void (^didfinishblock) (NSObject *ob);
This declares a block of type Didfinishblock,
Then it will be available
@property (nonatomic,copy) Didfinishblock Finishblock;
Declare a block object, note that the object property is set to copy, and a copy is automatically copied when the block parameter is received.
__block is a special type,
A local variable declared with this keyword can be changed by block, and its value in the original function will be changed.
4 Common series of questions
Interview, the interviewer will first ask, whether to understand the block, whether the use of blocks, these questions equal to the opening, often is the beginning of a series of questions, so be sure to truthfully according to their own circumstances to answer.
1 What are the advantages of using block and using delegate to complete the delegation mode?
The first thing to understand is the delegate mode, the delegate mode is applied extensively in iOS, it is the object adapter in the adapter mode in design mode, and the OBJECTIVE-C uses the ID type to point to all objects, which makes the delegate mode easier to implement in iOS. Learn the details of the delegate model:
iOS design mode----delegate mode
The advantage of using block to implement the delegate mode is that the block code of the callback is defined inside the delegate object function, which makes the code more compact;
An adaptation object no longer needs to implement a specific protocol, and the Code is more concise.
2 Multi-Threading with block
GCD and Block
Using the Dispatch_async series method, the block can be executed in the specified manner
GCD Programming Example
Full definition of Dispatch_async
void Dispatch_async (
dispatch_queue_t queue,
dispatch_block_t block);
Function: Commits an asynchronously executed block in the specified queue, without blocking the current thread
The thread that the block executes is controlled through the queue. The main thread executes the Finishblock object defined in the previous article
Dispatch_async (Dispatch_get_main_queue (), ^ (void) {Finishblock ();});
Reference blog:
http://blog.csdn.net/xunyn/article/details/11658261
Http://www.2cto.com/kf/201504/388349.html
Bo Master Weibo, Cocoachina blog, Pinterest sync Update, Welcome to pay attention to:
Sina Weibo: http://weibo.com/p/1005052308506177/home?from=page_100505_profile&wvr=6&mod=data&is_all=1# Place
Pinterest: Http://www.jianshu.com/users/63baf9271d14/latest_articles
cocoachina:http://blog.cocoachina.com/477998
On the block of iOS