为什么在Swift中dispatch_queue_create会给出EXC_BAD_ACCESS错误? [英] Why does dispatch_queue_create give an EXC_BAD_ACCESS error in Swift?

查看:202
本文介绍了为什么在Swift中dispatch_queue_create会给出EXC_BAD_ACCESS错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将使用Grand Central Dispatch的一些代码从C ++移植到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(代码= 1,地址= 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.

有人可以在这里帮助我吗?

Can anyone please help me out here?

推荐答案

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_SERIALnil传递给串行队列 (对于并发队列,则为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是 不是有效的属性.所以传递0nil是 在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.

这篇关于为什么在Swift中dispatch_queue_create会给出EXC_BAD_ACCESS错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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