问题描述
我正在将一些代码从 C++ 移植到使用 Grand Central Dispatch 的 Swift,我发现 dispatch_queue_create 的一个奇怪错误似乎根本不起作用.
I am porting some code from C++ to Swift that used Grand Central Dispatch, and I am finding a curious error with dispatch_queue_create seemingly not working at all.
例如,在我的 C++ 基类头文件中,我会声明
For instance, in my C++ base class header, I would declare
dispatch_queue_t m_WorkQ;
然后在初始化器中放入
m_ResultQ = dispatch_queue_create("com.myapp.mHitsUpdateQueue", 0);
...一切都很美好.
我已经在 Swift 中尝试过,在我的班级中,在班级级别声明了这一点:
I've tried this in Swift, in my class, declaring this at class level:
var resultQueue: dispatch_queue_t
...在初始化程序中,我(除其他外)有一行
... and in the initalizer, I have (among others) the line
resultQueue = dispatch_queue_create("com.myapp.mHitsUpdateQueue", 0)
...它编译并启动正常,但在上面的行上给我一个 EXC_BAD_ACCESS (code=1, address = 0x37) 的即时运行时错误
... and it compiles and starts up fine, but gives me an immediate runtime error of EXC_BAD_ACCESS (code=1, address = 0x37) on the above line
为了确定它是否是我所做的其他任何事情,我创建了一个命令行工具应用程序,仅包含以下代码:
To determine if it's anything else I've done, I created a command line tool application consisting only of the following code:
import Foundation
var thisQueue = dispatch_queue_create("com.myApp.mHitsUpdateQueue", 0)
println(thisQueue.description)
...果然,我在thisQueue"分配行上得到了上述错误.所以我很确定我缺少关于 Swift 和 GCD 队列创建的一些非常明显的东西.
... and sure enough, I get the above error right on the "thisQueue" assignment line. So I'm pretty sure there's something really obvious about Swift and GCD queue creation that I'm missing.
谁能帮帮我?
推荐答案
dispatch_queue_create()
的第二个参数有类型dispatch_queue_attr_t
,声明为
The second argument of dispatch_queue_create()
has the type
dispatch_queue_attr_t
, which is declared as
typealias dispatch_queue_attr_t = NSObject
您必须为串行队列传递 DISPATCH_QUEUE_SERIAL
或 nil
(或 DISPATCH_QUEUE_CONCURRENT
用于并发队列):
You have to pass DISPATCH_QUEUE_SERIAL
or nil
for a serial queue
(or DISPATCH_QUEUE_CONCURRENT
for a concurrent queue):
var thisQueue = dispatch_queue_create("com.myApp.mHitsUpdateQueue", DISPATCH_QUEUE_SERIAL)
在 C(++) 中,可以传递 0
而不是 NULL
指针.
In C(++), 0
can be passed instead of a NULL
pointer.
然而,Swift 编译器将整数 0
包装到 NSNumber
对象中以便它可以传递给期望 NSObject
的函数范围.这会导致运行时异常,因为 NSNumber
是不是有效的属性.所以传递 0
或 nil
是在 Swift 中明显不同.
The Swift compiler, however, wraps the integer 0
into an NSNumber
object
so that it can be passed to the function expecting an NSObject
parameter. That causes the runtime exception because NSNumber
is
not a valid attribute. So passing 0
or nil
is
significantly different in Swift.
这篇关于为什么 dispatch_queue_create 在 Swift 中会给出 EXC_BAD_ACCESS 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!