1

刚刚开始使用块......非常混乱。我正在使用这样的块:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *myDictionary = [[mySingleton arrayPeopleAroundMe] objectAtIndex:indexPath.row];

NSMutableString *myString = [[NSMutableString alloc] initWithString:@"http://www.domain.com/4DACTION/PP_profileDetail/"];
[myString appendString:[myDictionary objectForKey:@"userID"]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[myString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]
                                            cachePolicy:NSURLRequestUseProtocolCachePolicy
                                        timeoutInterval:60.0];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection
 sendAsynchronousRequest:urlRequest
 queue:queue
 completionHandler: ^( NSURLResponse *response,
                      NSData *data,
                      NSError *error)
 {
     [[mySingleton dictionaryUserDetail] removeAllObjects];
     [[mySingleton arrayUserDetail] removeAllObjects];

     if ([data length] > 0 && error == nil) // no error and received data back
     {
         NSError* error;
         NSDictionary *myDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
         [mySingleton setDictionaryUserDetail:[myDic mutableCopy]];

         NSArray *myArray = [myDic objectForKey:@"searchResults"];
         [mySingleton setArrayUserDetail:[myArray mutableCopy]];

         [self userDetailComplete];
     } else if
         ([data length] == 0 && error == nil) // no error and did not receive data back
     {
         [self serverError];
     } else if
         (error != nil) // error
     {
         [self serverError];
     }
 }];
}

一旦连接完成,这被称为:

-(void)userDetailComplete {
ViewProfile *vpVC = [[ViewProfile alloc] init];
[vpVC setPassedInstructions:@"ViewDetail"];
[[self navigationController] pushViewController:vpVC animated:YES];
}

导致此错误弹出:“尝试从主线程或Web线程以外的线程获取Web锁。这可能是从辅助线程调用UIKit的结果。” 我摆脱错误的唯一方法是将 userDetailComplete 更改为:

-(void)userDetailComplete {
dispatch_async(dispatch_get_main_queue(), ^{
ViewProfile *vpVC = [[ViewProfile alloc] init];
[vpVC setPassedInstructions:@"ViewDetail"];
[[self navigationController] pushViewController:vpVC animated:YES];
});
}

我的问题:每次使用块时都会自动启动一个新线程吗?使用积木时我还应该注意哪些其他陷阱?

4

1 回答 1

7

块不创建线程。它们是闭包;它们只包含可在将来某个时间点运行的可运行代码。

这是在后台线程上运行的,因为这是您要求它执行的操作:

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection
  sendAsynchronousRequest:urlRequest
  queue:queue
  ...

您创建了一个新队列,然后要求NSURLConnection在该队列上给您回电。如果您想在主线程上被回调,请通过[NSOperationQueue mainQueue]. 这通常是你想要的。

于 2013-04-05T22:03:34.993 回答