iOS Block

一、先看一下block 结构。



二、再看代码。

//  无任何 传参的 block
    void(^noParameterBlock)(void) = ^{
        NSLog(@"I'm a block!");
    };
    
//  仅有 传参的 block
    void(^numberBlock)(NSInteger) = ^(NSInteger a){
        NSLog(@"I'm a block! a = %@", @(a));
    };
    
    numberBlock(10);
    
//  带返回值 block 和传参
    NSString * ( ^ myBlock )( int );
    
    myBlock = ^( int paramA )
    {
        return [ NSString stringWithFormat: @"Passed number: %i", paramA ];
    };
    
    NSString * numberStr= myBlock(7);
    
    NSLog(@"numberStr = %@  ",numberStr);
    
    /*
     从以上的事例,我们可以看出block 使用方式。
     blcok 写法格式为
     
     返回值类型 (^ block方法名)(传入值类型)=^(传入值){ 想做什么事方法实现 }
     
     */

    
//    测试 block 1、全局变量
    
        static int outA = 8;
        int (^myPtr)(int) = ^(int a){return outA + a;};
        outA = 10;
        int result_z = myPtr(3);  //result的值是8,因为outA是static类型的变量
        NSLog(@"result=%d", result_z);
    
//    测试 block 2、局部变量
    int outB = 8;
    int (^myPtrB)(int) = ^(int a){return outB + a;};
    outA = 10;
    int result_b = myPtrB(3);  //result的值是11
    NSLog(@"result=%d", result_b);
    
//   测试 block 3 、在Block使用中,Block内部能够读取外部局部变量的值。但我们需要改变这个变量的值时,我们需要给它附加上__bloc修饰符。还有为了避免某些情况下,Block循环引用的问题,我们也可以给相应对象加上__block 修饰符。
    __block int num = 5;
    
    int (^myPtr1)(int) = ^(int a){
        return num++;};
    
    int (^myPtr2)(int) = ^(int a){
        return num++;};
    
    int result1 = myPtr1(0);   //result的值为5,num的值为6
    int result2 = myPtr2(0);      //result的值为6,num的值为7
    
    NSLog(@" result=%d n,result=%d", result1,result2);
   //   访问某个类里的局部变量
    [self test_Block_method:^(NSString *operation, NSError *error) {
        NSLog(@"operation:%@    error:%@",operation,error);
    }];
 
// block 合体 传值
-(void)test_Block_method:(void (^)(NSString *, NSError *))failure
{
    NSError *error=[NSError errorWithDomain:@"Error=block 合体开始" code:1998 userInfo:nil];
    if (failure) {
        failure(@"1 operation \n",error);
    }
    
}


本文demo下载地址:http://download.csdn.net/download/nslong/8557691

参考地址:

http://www.devtalking.com/articles/you-should-know-block/

http://www.cocoachina.com/ios/20130711/6575.html


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值