OC学习-----代码块与并发性

代码块和并发性


1.代码块

传统的函数指针:void (*my_func)(void);
代码块的定义:将*换成^

1.1 举例:
int (^square_block)(int number) = ^(int num){return num*num;};

int result = square_block(6);
printf("Result = %d\n", result);

实现方式:

<returntype> (^blockname)(list of arguments) = ^(arguments){ body; };

返回类型,参数表都是可以省略的部分,如下例一个极简代码块:

void (^theBlock)() = ^{ printf("Hello World\n"); };
1.2 代码块的使用
  • 同一般函数直接通过函数名调用;
  • 直接将代码块当做参数;

2.并发性

核心方法:GCD

2.1 NSObject提供的方法

performSelectorInBackground:withObject:能够创建一个线程在后台运行方法;
限制:

  • 必须创建自动释放池
  • 方法不能有返回值,至多有一个参数

示例:

//方法函数定义
-(void) myBackgroundMethod:(id)myObject
{
    @autoreleasepool
    {   
        NSLog(@"My background method %@",myObject);
    }
}

//方法调用
[self performSelectorInBackground:@selector(myBackgroundMethod) withObject:argumentObject];
2.2 调度队列

使用方法: 实现方法代码,然后为其指派一个队列

  • 连续队列
  • 并发队列
  • 主队列

1)连续队列:一连串任务按照一定顺序执行,先入先出;

//第一个参数为队列名称,第二个参数为队列特性
dispatch_queue-t myQueue;
myQueue = dispatch_queue_create("queueName",NULL);

2)并发队列:系统提供3种:高优先级默认优先级低优先级

dispatch_queue-t myQueue;
myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0);

3)主队列:使用dispatch_get_main_queue可以访问与应用程序主线程有关的连续队列;

dispatch_queue-t myQueue;
myQueue = dispatch_get_current_queue(void);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值