本文介绍了使用块的目的是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序中使用块,但我真的不知道任何关于块。

I want to use blocks in my application, but I don't really know anything about blocks. Can anyone explain how and why I should use blocks in my code?

推荐答案

块是,但是你喜欢称它们)。它们的目的是使用块,程序员不必在全局范围中创建命名的函数,或提供目标动作回调,而是他/她可以创建一个未命名的局部函数,它可以访问其包含的变量范围和容易执行操作。

Blocks are closures (or lambda functions, however you like to call them). Their purpose is that using blocks, the programmer doesn't have to create named functions in the global scope or provide a target-action callback, instead he/she can create an unnamed, local "function" which can access the variables in its enclosing scope and easily perform actions.

例如,当你想要e。 G。调度一个异步操作,如动画的视图,没有阻塞,你想通知竞争对手,你必须写:

For example, when you want to e. g. dispatch an asynchronous operation, such an animation for views, without blocks, and you wanted to be notified of the competion, you had to write:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:context:)];
.... set up animation ....
[UIView commitAnimations];

这是很多代码,此外它意味着存在一个有效的 self 指针 - 这可能不总是可用(我体验这样的事情,当我正在开发MobileSubstrate-tweaks)。所以,除了这个,你可以使用从iOS 4.0及以后的块:

This is a lot of code, furthermore it implies the presence of a valid self pointer - that might not always be available (I experience such a thing when I was developing MobileSubstrate-tweaks). So, instead of this, you can use blocks from iOS 4.0 and onwards:

[UIView animateWithDuration:1.0 animations:^{
    // set up animation
} completion:^{
    // this will be executed on completion
}];

或者,例如,使用NSURLConnection ... B加载在线资源。 (Blocks之前):

Or, for example, loading online resources with NSURLConnection... B. b. (Before Blocks):

urlConnection.delegate = self;

- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)rsp
{
    // ...
}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
    // ...
}

// and so on, there are 4 or 5 delegate methods...

A。 B.(Anno Blocks):

A. B. (Anno Blocks):

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rsp, NSData *d, NSError *e) {
   // process request here
}];

更容易,更干净,更短。

Much easier, cleaner and shorter.

这篇关于使用块的目的是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 12:38