Can't subclass DispatchGroup - “only visible via the Objective-C runtime”?

亡梦爱人 提交于 2019-12-08 04:02:34

问题


It's not possible to subclass DispatchGroup, how to do so?

Note:

this has finally been fixed in iOS 10+

Example, carry a stateful package with a group,

class PushDispatchGroup: DispatchGroup {
    var sentIds: [(tableName: String, rowId: String)] = []
}

thanks to shallowThought for pointing out this is fixed in iOS10.


回答1:


how to inherit from a class which is 'only visible via the Objective-C runtime'?

You don't.

This is not wrapped around a proper "object" the way you're thinking about it. It's wrapped around a dispatch_group, which is a C struct. This class is not designed to be subclassed and does not bridge in a normal way to ObjC, so you can't subclass it there either.

"Objects" that bridge directly to low level C types often have very unusual structures that parts of the system are hard-coded to know how to deal with (this happens all the time with toll-free bridging like NSString and CFString). In many cases, the types are designed to be identical in memory layout through careful choice of structure (I haven't picked apart DispatchGroup, but it looks like one from this group). When that's true, you can't add any storage because then the memory layout will be different and you break the bridging.

As various commenters have said, you also shouldn't be doing this, which is why there is no easy answer for how to do this. Classes that are not explicitly designed for subclassing are intentionally difficult or impossible to subclass in Swift (this comes up regularly around less tricky types than DispatchGroup, and the answer is the same: it's intentional; don't do it).



来源:https://stackoverflow.com/questions/41210629/cant-subclass-dispatchgroup-only-visible-via-the-objective-c-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!