3

我使用MBProgressHUD作为指标。你知道它在执行其他方法时使用了一个单独的线程。当我想使用NSURLConnection时,它的委托没有正确调用。

这是我所拥有的(@implementation 文件):

- (void)viewDidLoad {
    [super viewDidLoad];
    [self hudShowWithLabel];
}

-(void)hudShowWithLabel {
    HUD = [[MBProgressHUD alloc] initWithView: self.view];
    [self.view addSubview:HUD];

    HUD.delegate = self;
    HUD.labelText = @"Loading";
    [HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}

-(void)myTask {
    responseData = [NSMutableData data];
    NSLog(@"Is%@ main thread", ([NSThread isMainThread] ? @"" : @" NOT"));
    NSString *requestURL = @"http://someurl";

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestURL]];
    (void)[[NSURLConnection alloc] initWithRequest:request delegate: self];    
}

运行时,我可以看到它myTask不在MainThread. 我该如何解决这个问题?

4

2 回答 2

2

您可以在主线程中启动 NSURLConnection:

[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:YES];

选择器开始是:

- (void)start
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestURL]];

    self.connection =[[NSURLConnection alloc] initWithRequest:request
                                                 delegate:self
                                         startImmediately:NO];
    [self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    [self.connection start];
}

github上也有一个例子。

于 2013-06-28T15:45:07.053 回答
0

NSURLConnection 在另一个应该有运行循环的线程中运行。您可以尝试在线程的 main 方法中添加这样的运行循环代码:

while (!finished)
{
  [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
}
于 2013-08-15T14:04:40.727 回答