Extending a Swift class with Objective C category

人走茶凉 提交于 2019-11-28 23:04:43

The Bad

i too have been fighting this issue a bunch. unfortunately the documentation pretty explicitly states that this pattern is not allowed:

To avoid cyclical references, don’t import Swift code into an Objective-C header (.h) file. Instead, you can forward declare a Swift class or protocol to reference it in an Objective-C interface.

Forward declarations of Swift classes and protocols can only be used as types for method and property declarations.

also throughout the the linked page you will notice it keeps mentioning to import the generated header specifically into the .m file:

To import Swift code into Objective-C from the same target

Import the Swift code from that target into any Objective-C .m file within that target

The Good

one solution that may work for you is to create a swift extension that redefines each method you need in the category. it is fragile and ugly, but arguably the cleanest solution.

/**
 Add category methods from objc here (since circular references prohibit the ObjC extension file)
 */
extension SomeClass {
    @nonobjc func someMethod() {
        self.performSelector(Selector("someMethod"))
    }
}
  • adding the @noobjc to the front allows the same method signature to be used w/o overriding the ObjC implementation
  • now the import "SomeClass+Extension.h" from the bridging header can be removed

if support for more than two input params is needed, or tighter type coupling is desired i would recommend using the runtime to call the underlying function. a great description is here.

From the Interoperability guide, we cannot directly access the subclassed / categorized / extensioned Objc-objects for the .swift [SomeClass] class.

But as a turn-around, we can do this:

For Variables , we can do this:

extension Class {
    private struct AssociatedKeys {
        static var DescriptiveName = "sh_DescriptiveName"
    }

    var descriptiveName: String? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String
        }

        set {
            if let newValue = newValue {
                objc_setAssociatedObject(
                    self,
                    &AssociatedKeys.DescriptiveName,
                    newValue as NSString?,
                    .OBJC_ASSOCIATION_RETAIN_NONATOMIC
                )
            }
        }
    }
}

For Methods, we can use method_swizzling which is not recommended.

As one simple solution, you can move the extension to your Swift code. Then you won't have any dependency problems.

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