< Objective-C >block

块(block)的用法

        //无参无返回值
        void (^message)(void) = ^{
            NSLog(@"Hello World!\n");
        };
        
        //有参有返回值
        NSString *(^repeat)(NSString *, int) = ^(NSString *str, int times) {
            NSMutableString *result = [NSMutableString string];
            for(int i=0; i<times; i++) {
                [result appendString:str];
            }
            return result;
        };
        
        message();
        NSString *str = repeat(@"Hello\n",3);
        NSLog(@"%@",str);        

 

block块内部可以读取块外部,所在方法范围内的变量

block不能修改读取的变量

如果要修改,必须在变量前使用__block(双下划线)修饰

posted @ 2015-06-09 20:21  aY_Wonder  阅读(124)  评论(0编辑  收藏  举报