【问题标题】:can we change a background thread operation to main thread?我们可以将后台线程操作更改为主线程吗?
【发布时间】:2013-09-10 10:46:33
【问题描述】:

如何在 viewDidLoad 的后台线程中执行 JSON 解析,并在单击按钮时将其移动到主线程。现在我尝试了

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


-(void)parseData    {

    MSJsonParser *parser = [[MSJsonParser alloc]initWithParserType:kCountriesParsing];
    parser._parserSource = self;
    [parser requestParsingWithUrl:COUNTRIES_URL ];

}

但我不知道如何将此后台进程更改为主线程。请帮帮我

【问题讨论】:

  • 你为什么要这么做?

标签: ios objective-c json background-thread


【解决方案1】:

你想在主线程上运行的方法部分,只要把它放在这个 GCD 块里面,它就会在主线程上运行:

dispatch_sync(dispatch_get_main_queue(), ^{
    //put stuff here
});

【讨论】:

  • 不确定我是否通过在后台解析它并单击一个按钮使其转到主线程来理解您的意思...听起来您正在尝试获取一种可能运行的方法在 2 个不同的线程上..
  • dispatch_sync 在执行块时不会阻塞发出调用的线程吗?
【解决方案2】:

在 NSThread 中查看 NSObject (NSThreadPerformAdditions)

 - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array;
 - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;

【讨论】:

    猜你喜欢
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多