ios block

一、什么是Blocks
     Block是一个C级别的语法以及运行时的一个特性,和标准C中的函数(函数指针)类似,但是其运行需要编译器和运行时支持,从ios4.0开始就很好的支持Block。

二、在ios开发中,什么情况下使用Block
     Block除了能够定义参数列表、返回类型外,还能够获取被定义时的词法范围内的状态(比如局部变量),并且在一定条件下(比如使用__block变量)能够修改这些状态。此外,这些可修改的状态在相同词法范围内的多个block之间是共享的,即便出了该词法范围(比如栈展开,出了作用域),仍可以继续共享或者修改这些状态。通常来说,block都是一些简短代码片段的封装,适用作工作单元,通常用来做并发任务、遍历、以及回调。

三、block如何申明(对比于c语言中的函数申明)

四、c函数指正和blocks调用
     int (*CFunc) (int a) 函数调用
     int result = CFunc(10);
     int (^BFunc)  (int  a)  函数调用
     int result = BFunc(10);

五、__block  关键字
     一个Block的内部时可以引用自身作用域外的变量的,包括static变量,extern变量或自由变量(定义一个变量的时候,如果不加存储修饰符,默认情况下就是自由变量auto,auto变量保存在stack中的。除了auto之外还存在register,static等存储修饰符),对于自由变量,在Block中只读的。在引入block的同时,还引入了一种特殊的__block关键字变量存储修饰符。

六、block的几个小例子


Java代码 复制代码  收藏代码
  1. #import <Cocoa/Cocoa.h>   
  2.   
  3.   
  4. int main(int argc, char *argv[])   
  5. {   
  6.     @autoreleasepool {   
  7.         NSLog(@"Hello world");   
  8.         void (^myblocks) (void) = NULL;   
  9.         myblocks = ^(void) {   
  10.             NSLog(@"in blocks");   
  11.         };   
  12.         NSLog(@"before myblocks");   
  13.         myblocks();   
  14.         NSLog(@"after myblocks");   
  15.            
  16.            
  17.         int (^myblocks2) (int a, int b) = ^(int a, int b) {   
  18.             int c = a + b;   
  19.             return c;   
  20.         };   
  21.         NSLog(@"before blocks2");   
  22.         int ret = myblocks2(1020);   
  23.         NSLog(@"after blocks2 ret %d", ret);   
  24.            
  25.         //此处如果不加__block会报错   
  26.         __blockint sum = 0;   
  27.         int (^myblocks3) (int a, int b) = ^(int a, int b) {   
  28.             sum = a + b;   
  29.             return3;   
  30.         };   
  31.         myblocks3(2030);   
  32.         NSLog(@"sum is %d", sum);   
  33.     }   
  34.     returnNSApplicationMain(argc, (constchar **)argv);   
  35. }  
#import <Cocoa/Cocoa.h>


int main(int argc, char *argv[])
{
    @autoreleasepool {
        NSLog(@"Hello world");
        void (^myblocks) (void) = NULL;
        myblocks = ^(void) {
            NSLog(@"in blocks");
        };
        NSLog(@"before myblocks");
        myblocks();
        NSLog(@"after myblocks");
        
        
        int (^myblocks2) (int a, int b) = ^(int a, int b) {
            int c = a + b;
            return c;
        };
        NSLog(@"before blocks2");
        int ret = myblocks2(10, 20);
        NSLog(@"after blocks2 ret %d", ret);
        
        //此处如果不加__block会报错
        __blockint sum = 0;
        int (^myblocks3) (int a, int b) = ^(int a, int b) {
            sum = a + b;
            return3;
        };
        myblocks3(20, 30);
        NSLog(@"sum is %d", sum);
    }
    returnNSApplicationMain(argc, (constchar **)argv);
}

打印结果如下
2012-09-03 10:23:20.878 blockTest[407:403] Hello world
2012-09-03 10:23:20.880 blockTest[407:403] before myblocks
2012-09-03 10:23:20.881 blockTest[407:403] in blocks
2012-09-03 10:23:20.881 blockTest[407:403] after myblocks
2012-09-03 10:23:20.882 blockTest[407:403] before blocks2
2012-09-03 10:23:20.882 blockTest[407:403] after blocks2 ret 30
2012-09-03 10:23:20.882 blockTest[407:403] sum is 50

七、block写的回调例子
1、Dog.h
Java代码 复制代码  收藏代码
  1. #import <Foundation/Foundation.h>   
  2.   
  3.   
  4. @interface Dog : NSObject {   
  5.     int _ID;   
  6.     NSTimer *timer;   
  7.     int barkCount;   
  8.        
  9.     //定义一个blocks变量   
  10.     void (^BarkCallback) (Dog *thisDog, int count);   
  11. }   
  12. @property (assign) int ID;   
  13.   
  14.   
  15. //向外暴露一个接口   
  16. -(void) setBark:( void (^) (Dog *thisDog, int count) ) eachBark;   
  17.   
  18.   
  19. @end  
#import <Foundation/Foundation.h>


@interface Dog : NSObject {
    int _ID;
    NSTimer *timer;
    int barkCount;
    
    //定义一个blocks变量
    void (^BarkCallback) (Dog *thisDog, int count);
}
@property (assign) int ID;


//向外暴露一个接口
-(void) setBark:( void (^) (Dog *thisDog, int count) ) eachBark;


@end

2、Dog.m
Java代码 复制代码  收藏代码
  1. #import "Dog.h"  
  2.   
  3.   
  4. @implementation Dog   
  5. @synthesize ID = _ID;   
  6.   
  7.   
  8. -(id) init   
  9. {   
  10.     self = [superinit];   
  11.     if (self) {   
  12.         //每隔1s调用一次updateTimer方法   
  13.         timer = [NSTimerscheduledTimerWithTimeInterval:1.0ftarget:selfselector:@selector(updateTimer:) userInfo:nilrepeats:YES];   
  14.            
  15.     }   
  16.     returnself;   
  17. }   
  18.   
  19.   
  20. -(void) updateTimer:(id) arg   
  21. {   
  22.     barkCount ++;   
  23.     NSLog(@"dog %d bark count %d", _ID, barkCount);   
  24.     //向Person对象进行汇报   
  25.     if (BarkCallback) {   
  26.         //调用从Person传过来的Blocks   
  27.         BarkCallback(self, barkCount);   
  28.     }   
  29. }   
  30.   
  31.   
  32.   
  33.   
  34. -(void) setBark:(void (^)(Dog *, int))eachBark   
  35. {   
  36.     [BarkCallbackrelease];   
  37.     BarkCallback = [eachBark copy];   
  38. }   
  39.   
  40.   
  41. -(void) dealloc   
  42. {   
  43.     [BarkCallbackrelease];   
  44.     [superdealloc];   
  45. }   
  46. @end  
#import "Dog.h"


@implementation Dog
@synthesize ID = _ID;


-(id) init
{
    self = [superinit];
    if (self) {
        //每隔1s调用一次updateTimer方法
        timer = [NSTimerscheduledTimerWithTimeInterval:1.0ftarget:selfselector:@selector(updateTimer:) userInfo:nilrepeats:YES];
        
    }
    returnself;
}


-(void) updateTimer:(id) arg
{
    barkCount ++;
    NSLog(@"dog %d bark count %d", _ID, barkCount);
    //向Person对象进行汇报
    if (BarkCallback) {
        //调用从Person传过来的Blocks
        BarkCallback(self, barkCount);
    }
}




-(void) setBark:(void (^)(Dog *, int))eachBark
{
    [BarkCallbackrelease];
    BarkCallback = [eachBark copy];
}


-(void) dealloc
{
    [BarkCallbackrelease];
    [superdealloc];
}
@end


3、Person.h
Java代码 复制代码  收藏代码
  1. #import <Foundation/Foundation.h>   
  2. #import "Dog.h"  
  3.   
  4.   
  5. @interface Person : NSObject   
  6. {   
  7.     Dog *_dog;   
  8. }   
  9.   
  10.   
  11. @property (retain) Dog *dog;   
  12.   
  13.   
  14. @end  
#import <Foundation/Foundation.h>
#import "Dog.h"


@interface Person : NSObject
{
    Dog *_dog;
}


@property (retain) Dog *dog;


@end


4、Person.m

Java代码 复制代码  收藏代码
  1. #import "Person.h"  
  2.   
  3.   
  4. @implementation Person   
  5. @synthesize dog = _dog;   
  6.   
  7.   
  8. -(void) setDog:(Dog *)dog   
  9. {   
  10.     if (_dog != dog) {   
  11.         [_dogrelease];   
  12.         _dog = [dog retain];   
  13.            
  14.         [_dogsetBark:^(Dog *thisDog, int count) {   
  15.             NSLog(@"person dog %d count %d", [thisDog ID], count);   
  16.         }];   
  17.     }   
  18. }   
  19.   
  20.   
  21. -(Dog *) dog   
  22. {   
  23.     return_dog;   
  24. }   
  25.   
  26.   
  27. -(void) dealloc   
  28. {   
  29.     self.dog = nil;   
  30.     [superdealloc];   
  31. }   
  32.   
  33.   
  34. @end  
#import "Person.h"


@implementation Person
@synthesize dog = _dog;


-(void) setDog:(Dog *)dog
{
    if (_dog != dog) {
        [_dogrelease];
        _dog = [dog retain];
        
        [_dogsetBark:^(Dog *thisDog, int count) {
            NSLog(@"person dog %d count %d", [thisDog ID], count);
        }];
    }
}


-(Dog *) dog
{
    return_dog;
}


-(void) dealloc
{
    self.dog = nil;
    [superdealloc];
}


@end



5、Main.m
Java代码 复制代码  收藏代码
  1. #import <Foundation/Foundation.h>   
  2. #import "Person.h"  
  3. #import "Dog.h"  
  4.   
  5.   
  6. int main(int argc, constchar * argv[])   
  7. {   
  8.   
  9.   
  10.     @autoreleasepool {   
  11.            
  12.         // insert code here...   
  13.         NSLog(@"Hello, World!");   
  14.         Person *person = [[Personalloc] init];   
  15.         Dog *dog = [[Dogalloc] init];   
  16.         [dog setID:10];   
  17.         [person setDog:dog];   
  18.         [dog release];   
  19.         while (1) {   
  20.             [[NSRunLoopcurrentRunLoop] run];   
  21.         }   
  22.         [person release];   
  23.            
  24.     }   
  25.     return 0;   
  26. }  
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Dog.h"


int main(int argc, constchar * argv[])
{


    @autoreleasepool {
        
        // insert code here...
        NSLog(@"Hello, World!");
        Person *person = [[Personalloc] init];
        Dog *dog = [[Dogalloc] init];
        [dog setID:10];
        [person setDog:dog];
        [dog release];
        while (1) {
            [[NSRunLoopcurrentRunLoop] run];
        }
        [person release];
        
    }
    return 0;
}


6、打印结果
2012-09-03 11:21:08.551 blockDelegate[549:403] Hello, World!
2012-09-03 11:21:09.554 blockDelegate[549:403] dog 10 bark count 1
2012-09-03 11:21:09.555 blockDelegate[549:403] person dog 10 count 1
2012-09-03 11:21:10.554 blockDelegate[549:403] dog 10 bark count 2
2012-09-03 11:21:10.555 blockDelegate[549:403] person dog 10 count 2
2012-09-03 11:21:11.553 blockDelegate[549:403] dog 10 bark count 3
2012-09-03 11:21:11.554 blockDelegate[549:403] person dog 10 count 3
2012-09-03 11:21:12.554 blockDelegate[549:403] dog 10 bark count 4
2012-09-03 11:21:12.555 blockDelegate[549:403] person dog 10 count 4
2012-09-03 11:21:13.553 blockDelegate[549:403] dog 10 bark count 5
2012-09-03 11:21:13.553 blockDelegate[549:403] person dog 10 count 5
2012-09-03 11:21:14.553 blockDelegate[549:403] dog 10 bark count 6
2012-09-03 11:21:14.554 blockDelegate[549:403] person dog 10 count 6
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值