在后台和主线程ios中执行

时间:2011-03-07 07:08:31

标签: multithreading ios background execution

我有一个函数foo(),它在后台线程上调用一个函数栏 foo() {

  [self performSelectorInBackground:@selector(bar:) withObject:nil];

}

 bar()
{
//some initialsations
//calling another function
bar1();//also in background
 //after bar1() returns
 //marking following statement with *       
      [self performSelectorOnMainThread:@selector(stopActivityIndicator:)withObject:nil     wailUntilDone:YES];

  }

[self performSelectorInBackground:@selector(bar:) withObject:nil]; bar()在调用另一个函数之前做了一些事情。 bar()所做的就是在后台。同时,我正在展示ActivityIndi​​cator。一旦我的函数在bar()中返回,我就会在MainThread上调用一个stopActivityIndi​​cator函数。

现在,我想在调用stopActivityIndi​​cator()之前调用MainThread中的另一个函数 我该怎么做? 我可以再放一个 bar() { //some initialsations //calling another function bar1();//also in background //after bar1() returns //marking following statement with * [self performSelectorOnMainThread:@selector(stopActivityIndicator:)withObject:nil wailUntilDone:YES]; }      之前*?

1 个答案:

答案 0 :(得分:2)

您可以调度一个块以在主线程上运行,并将您需要的任何代码放入该块中:

[[NSOperationQueue mainQueue] addOperationWithBlock:^ {

   // Code here
   NSLog(@"This is the main thread");

}];

使用您的代码,即成为:

bar()
{
    bar1();

    [[NSOperationQueue mainQueue] addOperationWithBlock:^ {
        [stopActivityIndidator];
        [functionIWant];
    }];
}