blocks 循环引用问题

原文地址  http://blog.sina.com.cn/s/blog_79a120e501018vrn.html




什么是block?

代码块:{}里的东西
block可以想id一样装到array里,dictionary里。。。但是不能对他发送消息。

nsdictionary 里有一个方法:enumerateKeysAndObjectUs ingBlock:^(id key,id value,BOOL *stop)
这个方法遍历dictionary里的东西,直到*stop = YES为止。

block 里的代码对于主线程里的变量什么的都是可读的。除非主线程里的变量加上__block
例如:__block BOOL something;
这样something变量就可以用了。


block代码块里用到的东西,比如主线程里的全局变量,局部变量,UI等,block都会对它指向一个strong指针。也就是说,局部变量所在的局部代码运行完后,局部变量不会释放,直到block消失,它才释放。

这个不太好,这样如果block代码里面有self.something,而block又存储在strong的全局变量里,会导致block对self一个strong指针,self对block又有一个strong指针,就导致了memory circle。相应的解决办法是:
__weak MyClass *weakself = self;
使得block指向self一个弱指针。self指向block仍旧是强指针。这样一个是弱的便解决问题了。

block的定义方法:
rypedef double (^unary_operation_t)(double op);

unary_operation_t square;
square = ^(double operand){
         return operand * operand;
}

block调用:
double squareOfFive = square(5.0);


block不用typedef的定义方法:
double (^square)(double op) = ^(double op){return op * op;}

block直接在方法里定义:
- (void)enumerateKeysAndObjectsUsingBlock:(void (^)(id key,id obj,BOOL *stop))block;

block没有注明返回值的时候,默认返回值是参数的类型,定义方式:
^(double operand){
        return operand;
}

block没有参数,没有返回值:
^{}

Grand Central Dispatch (GCD)API
GCD IS A C API

method:
creating and releasing queues
dispatch_queue_t dispatch_queue_create(const char *label,NULL);    //create
void dispatch_release(dispatch_queue_t);                                       //release

put blocks in the queue
typedef void (^dispatch_block_t)(void);
void dispatch_async(dispatch_queue_t queue, dispatch_block_t block); //the block into the queue

get the current or main queue
dispatch_queue_t dispatch_get_current_queue();
void dispatch_queue_retain(dispatch_queue_t);    //keep it in the heap until dispatch_release

dispatch_queue_t dispatch_get_main_queue();      //get the main queue


- (void)viewWillAppear:(BOOL)animated
    dispatch_queue_t downloadQueue = dispatch_queue_create(“image downloader”, NULL);
    dispatch_async(downloadQueue, ^{ NSData *imageData = [NSData dataWithContentsOfURL:networkURL];    
    dispatch_async(dispatch_get_main_queue(), ^{
    UIImage *image = [UIImage imageWithData:imageData];
    self.imageView.image = image;
    self.imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    self.scrollView.contentSize = image.size; });
   }); 
   dispatch_release(downloadQueue);

} 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值