Why does dispatch_queue_create give an EXC_BAD_ACC

2019-02-25 01:13发布

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.

For instance, in my C++ base class header, I would declare

dispatch_queue_t m_WorkQ;

and in the initializer, put

m_ResultQ = dispatch_queue_create("com.myapp.mHitsUpdateQueue", 0);

... and everything was glorious.


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)

... 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)

... 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?

1条回答
Deceive 欺骗
2楼-- · 2019-02-25 02:15

The second argument of dispatch_queue_create() has the type dispatch_queue_attr_t, which is declared as

typealias dispatch_queue_attr_t = NSObject

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)

In C(++), 0 can be passed instead of a NULL pointer.

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.

查看更多
登录 后发表回答