Objective-C之Blocks

简介:

OC中Blocks(块)相当于其他语言C#,AS等等中的方法嵌套的方法。所以它写在函数或者方法的内部。块是以“^”为标识的。
如 :

^(void)
{
                NSLog(@"I am Aonaufly");
}

^后面的括号之中是一个参数列表 , 因为没有参数所以写void。
通用 , 可以将一个块声明成一个变量:

        void (^print_message)(void) = ^(void){
            NSLog(@"I am Aonaufly");
        };

意思是:
等号(=)左边的print_message 没有参数和返回值的块。
在main中声明并调用一下:
Objective-C之Blocks

结果为:
Objective-C之Blocks

现在来看看带参数的情况:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        void (^hasParam)(int) = ^( int u ){
            NSLog(@"param is %d" , u);
        };
        hasParam(12);
    }
    return 0;
}

可以看出:
hasParam只是给出了参数的类型(多个参数使用,隔开),并没有给出参数的名称 。而在右边的块中就相对应的给出了参数类型及其参数名称。
结果为:
Objective-C之Blocks

如何写带有返回值的块。

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        int (^hasParam)(int) = ^( int u ){
            return u;
        };
        NSLog(@"hasParam return is %d" , hasParam(12));
    }
    return 0;
}

可以看出 : 如果想要有返回值 , 则直接在等号最左边加一个返回的类型 , 本例返回的是int:
Objective-C之Blocks

结果:
Objective-C之Blocks








本文转自Aonaufly51CTO博客,原文链接:http://blog.51cto.com/aonaufly/2049167,如需转载请自行联系原作者


相关文章
|
C++ 存储 iOS开发
|
iOS开发
谈Objective-C Block的实现
来源:http://blog.devtang.com/blog/2013/07/28/a-look-inside-blocks/ 前言 这里有关于block的5道测试题,建议你阅读本文之前先做一下测试。
1000 0
|
安全 iOS开发 编译器
Effective Objective-C 2.0
本书是iOS开发进阶的必读书籍之一。文中部分名词的中文翻译略坑,比如对block和GCD的翻译。其他整体还好,原作者写的比较用心。代码规范讲了不少,底层原理讲了一点点,且主要集中在第二章。
1405 0
The Building Blocks of a B-Spline
B样条曲线比Bezier曲线更灵活,它的灵活性来自于你对基函数灵活地控制。我将对B样条的各组成部分进行讲解,首先讲一下控制顶点(Control Points)。 Control Points 控制顶点 Bezier曲线的控制顶点对整条曲线都有影响,即改变某一顶点的位置,对整条曲线都有影响,因而Bezier曲线不具有局部修改性。
1154 0
Combination Sum
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
748 0
Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
723 0
uva 101 - The Blocks Problem
点击打开链接 题目意思: 在早期人工智慧的領域中常常會用到機器人,在這個問題中有一支機器手臂接受指令來搬動積木,而你的任務就是輸出最後積木的情形。
779 0
uva101 The Blocks Problem
uva101 The Blocks Problem
66 0

热门文章

最新文章