Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Objective-C中的Block(块)详解

Block初探在Objective-c中NSArray是很常用的容器之一,很多时候我们需要对数组中的数据进行排序,因此与下面类似的代码会经常碰到:NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {
 
    if ([obj1 integerValue] > [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }
 
    if ([obj1 integerValue] < [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];刚接触objc的朋友可能会对这段代码表示看不懂,sortedArrayUsingComparator: ^(id obj1, id obj2) {
    // 代码省略
}];这个以^开头的参数类型为NSComparetor,原型如下 : typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);其实这个Comparetor的功能就类似于C语言中的函数指针,以及C++11、Java 8 、C#等语言中的Lambda表达式。其返回值的类型为NSComparionResult,参数为两个id类型的变量,类型名为NSComparetor。Objective-C中@property的所有属性详解 http://www.linuxidc.com/Linux/2014-03/97744.htmObjective-C 和 Core Foundation 对象相互转换的内存管理总结 http://www.linuxidc.com/Linux/2014-03/97626.htm使用 Objective-C 一年后我对它的看法 http://www.linuxidc.com/Linux/2013-12/94309.htm10个Objective-C基础面试题,iOS面试必备 http://www.linuxidc.com/Linux/2013-07/87393.htmObjective-C适用C数学函数 <math.h> http://www.linuxidc.com/Linux/2013-06/86215.htmC语言中的函数指针我们首先来回顾一下C语言中的最简单的函数指针,在C语言中我们以 returntype (*name) (arg);的格式定义一个函数指针变量。或者以 typedef的形式定义一个函数指针类型。示例代码如下 : // C语言的函数指针声明
int (*addInC)(int , int ) ;// 声明一个函数指针类型,类型名为AddOperation
typedef int (*AddOperation)(int, int);// 普通C语言函数
int doAdd(int a, int b) {
    return a + b ;
}//
int main(int argc, const char * argv[])
{    @autoreleasepool {
        // addInC指针变量指向doAdd函数
        addInC = doAdd;
        // 函数指针调用,实际上调用的是doAdd(5,6)
        NSLog(@" addInC : %i.", addInC(5, 6)) ;
        // 声明一个aop函数指针变量,也指向doAdd
        AddOperation aop = doAdd ;
        NSLog(@" AddOperation : %i.", aop(100, 23) );
    }
    return 0;
}输出 : addInC : 11.
AddOperation : 123.首先是生命一个函数指针,addInC,然后在main函数中将addInC指向doAdd函数,这样调用addInC(5, 6)就等于调用了doAdd(5, 6)。同理AddOperation也是这个原理。Java 8中的Lambda表达式更多详情见请继续阅读下一页的精彩内容: http://www.linuxidc.com/Linux/2014-09/106142p2.htm