在iOS 3.x中等效的GCD串行调度队列 [英] Equivalent of GCD serial dispatch queue in iOS 3.x

查看:181
本文介绍了在iOS 3.x中等效的GCD串行调度队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apple的Grand Central Dispatch(GCD)非常棒,但仅适用于iOS 4.0或更高版本。 Apple的文档说,[A]序列化操作队列不提供与Grand Central Dispatch中的串行调度队列完全相同的行为(因为队列不是FIFO,但顺序由依赖关系和优先级决定)。

Apple's Grand Central Dispatch (GCD) is great, but only works on iOS 4.0 or greater. Apple's documentation says, "[A] serialized operation queue does not offer quite the same behavior as a serial dispatch queue in Grand Central Dispatch does" (because the queue is not FIFO, but order is determined by dependencies and priorities).

在GCD发布之前支持操作系统版本时,实现与GCD串行调度队列相同效果的正确方法是什么?或者换句话说,在想要支持小于4.0的版本的iOS应用程序中处理简单后台处理(执行Web服务请求等)的推荐方法是什么?

What is the right way to achieve the same effect as GCD's serial dispatch queues while supporting OS versions before GCD was released? Or put another way, what is the recommended way to handle simple background processing (doing web service requests, etc.) in iOS apps that want to support versions less than 4.0?

推荐答案

似乎人们需要付出很多努力来重写NSRunloop。根据 NSRunloop文档

Seems like people are going to a lot of effort to rewrite NSRunloop. Per the NSRunloop documentation:


您的应用程序无法创建
或显式管理NSRunLoop
对象。每个NSThread对象,包括应用程序的主
线程的
,都会自动为它创建一个NSRunLoop对象
,需要

Your application cannot either create or explicitly manage NSRunLoop objects. Each NSThread object, including the application’s main thread, has an NSRunLoop object automatically created for it as needed.

创建一个可用的队列肯定是微不足道的答案:

So surely the trivial answer would be, to create a usable queue:

- (void)startRunLoop:(id)someObject
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    [[NSRunLoop currentRunLoop] run];

    [pool release];
}

...

NSThread *serialDispatchThread = [[NSThread alloc] 
                   initWithTarget:self 
                   selector:@selector(startRunLoop:) 
                   object:nil];
[serialDispatchThread start];

要将任务添加到队列中:

To add a task to the queue:

[object
    performSelector:@selector(whatever:) 
    onThread:serialDispatchThread
    withObject:someArgument
    waitUntilDone:NO];

根据关于运行循环的线程编程指南部分


Cocoa定义了一个自定义输入源
,它允许你在任何线程上执行选择器
。 ...执行选择器请求是
在目标线程上序列化,
缓解许多
同步问题,可能
出现多个方法在一个线程上运行

Cocoa defines a custom input source that allows you to perform a selector on any thread. ... perform selector requests are serialized on the target thread, alleviating many of the synchronization problems that might occur with multiple methods being run on one thread.

所以你有一个明确的串行队列。当然,我的写作并不是很精彩,因为我已经告诉run循环永远运行,你可能更喜欢可以稍后终止的,但这些都很容易修改。

So you've got an explicitly serial queue. Of course, mine isn't fantastically written because I've told the run loop to run forever, and you may prefer one you can terminate later, but those are easy modifications to make.

这篇关于在iOS 3.x中等效的GCD串行调度队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆