Grand Central Dispatch
GCD为Grand Central Dispatch的缩写。 Grand Central Dispatch (GCD)是Apple开发的一个多核编程的较新的解决方法。在Mac OS X 10.6雪豹中首次推出,并在最近引入到了iOS4.0。 GCD是一个替代诸如NSThread等技术的很高效和强大的技术。GCD完全可以处理诸如数据锁定和资源泄漏等复杂的异步编程问题。 GCD可以完成很多事情,但是这里仅关注在iOS应用中实现多线程所需的一些基础知识。 在开始之前,需要理解是要提供给GCD队列的是代码块,用于在系统或者用户创建的的队列上调度运行。 声明一个队列 如下会返回一个用户创建的队列: dispatch_queue_t myQueue = dispatch_queue_create("com.iphonedevblog.post", NULL);其中,第一个参数是标识队列的,第二个参数是用来定义队列的参数(目前不支持,因此传入NULL)。 执行一个队列 如下会异步执行传入的代码: dispatch_async(myQueue, ^{ [self doSomething]; });其中,首先传入之前创建的队列,然后提供由队列运行的代码块。 声明并执行一个队列 如果不需要保留要运行的队列的引用,可以通过如下代码实现之前的功能: dispatch_async(dispatch_queue_create ("com.iphonedevblog.post", NULL), ^{ [self doSomething]; }); 暂停一个队列 如果需要暂停一个队列,可以调用如下代码。暂停一个队列会阻止和该队列相关的所有代码运行。 dispatch_suspend(myQueue); 恢复一个队列 如果暂停一个队列不要忘记恢复。暂停和恢复的操作和内存管理中的retain和release类似。调用dispatch_suspend会增加暂停计数,而dispatch_resume则会减少。队列只有在暂停计数变成零的情况下才开始运行。dispatch_resume(myQueue); 从队列中在主线程运行代码 有些操作无法在异步队列运行,因此必须在主线程(每个应用都有一个)上运行。UI绘图以及任何对NSNotificationCenter的调用必须在主线程长进行。在另一个队列中访问主线程并运行代码的示例如下:dispatch_sync(dispatch_get_main_queue(), ^{ [self dismissLoginWindow]; });注意,dispatch_suspend (以及dispatch_resume)在主线程上不起作用。
- (void)getAaaaMainInfo
{
dispatch_block_t block = ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *url=[NSString stringWithFormat:@"%@/interface/aaaa.php", severAddress];
ASIFormDataRequest*request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
//NSString *_JSon=[dict JSONRepresentation];
[request setTimeOutSeconds:REQUEST_TIME_OUT_SEC];
[request setRequestMethod:@"POST"];
NSMutableData *body = [NSMutableData data];
//[body appendData:[_JSon dataUsingEncoding:NSUTF8StringEncoding]];
[request appendPostData:body];
[request startSynchronous];
//解析返回字段
NSString *responseStr = [request responseString];
NSString *retCode = @"0";//1 表示请求成功 其它则失败
//请求有还回
NSArray *postResult = [responseStr JSONValue];
NSMutableArray *resultAry = nil;
if ([responseStr length] > 0 && postResult) {
retCode = @"1";
resultAry = [NSMutableArray arrayWithCapacity:2];
for (NSDictionary *dict in postResult) {
NSMutableDictionary *temDic = [[NSMutableDictionary alloc] initWithDictionary:dict];
[resultAry addObject:temDic];
[temDic release];
}
}
//进入主线程里操作
dispatch_async(dispatch_get_main_queue(), ^{
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:3];
[dict setObject:retCode forKey:@"returnCode"];
if ([retCode isEqualToString:@"1"]) {
[dict setObject:resultAry forKey:@"returnInfo"];
}
[[NSNotificationCenter defaultCenter] postNotificationName:RESPONSE_GET_ACTIVE_INFO
object:nil
userInfo:dict];
});
[pool drain];
};
dispatch_async(requestQueue, block);
}