addSubview等待其余的方法

时间:2012-09-23 20:32:47

标签: objective-c uiview

我想在打电话时立即显示我的观点。我不知道如何让视图显示。

-(IBAction) showProgress: (id) sender {
   progressViewController *progress = [[progressViewController alloc] initWithNibName:@"progressViewController" bundle:NULL];
   [self.view addSubview:progress.view];
   [self someFunctionWhichTakesAgesToBeDone];
}

从当前的UIViewController调用它。并且在长函数之后出现视图。如何在漫长的功能之前展示它?谢谢你的回答。

3 个答案:

答案 0 :(得分:1)

使用GCD(Grand Central Dispatch)这是最简单的方式(并由Apple推荐),代码将是:

-(IBAction) showProgress: (id) sender {
    progressViewController *progress = [[progressViewController alloc] initWithNibName:@"progressViewController" bundle:NULL];
    [self.view addSubview:progress.view];

    // Heavy work dispatched to a separate thread
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"dispatched");
        // Do heavy or time consuming work
        [self someFunctionWhichTakesAgesToBeDone];

        // When finished call back on the main thread:
        dispatch_async(dispatch_get_main_queue(), ^{
            // Return data and update on the main thread
        });
    });

}

这是两个街区。第一个在单独的线程上执行繁重的工作,然后在繁重的工作完成时调用第二个块,以便在主线程上完成更改和UI更新(如果需要)。

答案 1 :(得分:0)

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsobject_Class/Reference/Reference.html

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait`

使用

[self.view performSelectorOnMainThread:@selector(addSubview:) withObject:progress.view waitUntilDone:YES]

或把你的Sleep()函数(我希望它是其他任何东西,Sleep()func非常糟糕,因为它被告知)到另一个函数MySleepFunc并调用

[self performSelector:@selector(MySleepFunc) withObject:nil afterDelay:0.003]

而不是睡眠(3)。

答案 2 :(得分:0)

了解多线程。简而言之,有单个UI线程可以绘制,接受用户事件等。如果使用sleep()或任何其他阻塞方法暂停它,则不会显示/重绘任何内容,也不会处理任何事件。您必须从后台线程发出HTTP请求。