Extending a Swift class with Objective-C category

后端 未结 3 1951
迷失自我
迷失自我 2020-12-14 16:48

Im in a situation where I need to use Objective-C category to extend a Swift class. I\'ve done something as follows:

In \"SomeClass.swift\":

class So         


        
3条回答
  •  抹茶落季
    2020-12-14 17:19

    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.

提交回复
热议问题