Runtime error when using CoreFoundation objects in a swift NSObject subclass

守給你的承諾、 提交于 2019-11-28 13:40:30

Hmmmm, CGPath isn't AnyObject compatible, but Swift shouldn't be trying to convert my Swift array into an NSArray.

It has to. You said you want it to be ObjC compatible, and ObjC can't handle Swift arrays directly. So it has to convert it to an NSArray.

The short answer is that this is working exactly as documented. Since this is iOS, the solution, however, is trivial. Just switch to UIBezierPath (which is AnyObject compatible) rather than CGPath.

All objects in Swift that are compatible with Objective-C, use the full Objective-C runtime. This means that when you make a type that inherits from NSObject (or is defined as Objective-C compatible), its methods and properties use Messaging instead of linking at compile time to your method.

To receive a message, all purely Swift objects, like your array, must be converted to their Objective-C counter-part. This happens regardless of if you are currently using the object in Objective-C because no matter what, it uses messaging.

Therefore, if you make a class that inherits from NSObject, you must assume that all properties can be converted to an Objective-C counterparts. As you said in your question, you can achieve this by using UIBezierPath instead of CGPath.

ShadowLightz

From "Using Swift with Cocoa and Objective-C"

When you use a Swift class or protocol in Objective-C code, the importer replaces all Swift arrays of any type in imported API with NSArray.

So according to this, the array should not be converted to an NSArray. As it does, I also think you should file a bug report.

In the meantime, you could use the corresponding Cocoa-Class or wrap your CGPath in an extra object.

import UIKit

class MyClass: NSObject {

    var list = [CGPath]();

    override init() {
        list.append(CGPathCreateMutable());
    }
}

var instance = MyClass()
print(instance.list.count) // 1

It is probably the fact that you didn't import Foundaion, which is where NSObject is:

import Foundation

This is where NSObject is contained (as far as I know). Hope this helped. :)

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