原文地址 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){
}
block调用:
double squareOfFive = square(5.0);
block不用typedef的定义方法:
double (^square)(double op) = ^(double op){return op * op;}
block直接在方法里定义:
- (void)enumerateKeysAndObjectsU singBlock:(void (^)(id key,id obj,BOOL *stop))block;
block没有注明返回值的时候,默认返回值是参数的类型,定义方式:
^(double 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);
}