在Swift中的运行时创建符合Objective-C协议的Objective-C类的对象

时间:2019-01-11 06:44:24

标签: objective-c swift objective-c-runtime

我具有Objective-C协议和接口实现,如下所示:

@protocol Animal <NSObject>
-(void)walk;
@end

@interface Cat : NSObject<Animal>
@end

@implementation Cat
-(void)walk{}
@end

@interface Dog : NSObject<Animal>
@end

@implementation Dog
-(void)walk{}
@end

我试图在运行时使用实现协议“动物”的类的实例。此代码很快:

var classesCount = objc_getClassList(nil, 0)
let allClasses = UnsafeMutablePointer<AnyClass?>.allocate(capacity: Int(classesCount))
classesCount = objc_getClassList(AutoreleasingUnsafeMutablePointer(allClasses), classesCount)
for i in 0..<classesCount{
    let cls : AnyClass! = allClasses[Int(i)]
    if class_conformsToProtocol(cls, Animal.self){
        let instance = cls.self.init()
        instance.walk()
    }
}

尝试了许多从AnyClass,AnyObject和NSObject获取实例的方法。我在这样做时面临编译器错误。此代码段的错误是:

  

“必需”初始化程序“ init(arrayLiteral :)”必须由“ NSSet”的子类提供。

有没有办法获取“猫”和“狗”的实例?

1 个答案:

答案 0 :(得分:4)

让我们在noise上定义一个Animal方法进行测试:

@protocol Animal <NSObject>
- (NSString *)noise;
@end

此外,让我们使用普通的Swift数组保存类列表:

let allClassesCount = objc_getClassList(nil, 0)
var allClasses = [AnyClass](repeating: NSObject.self, count: Int(allClassesCount))
allClasses.withUnsafeMutableBufferPointer { buffer in
    let autoreleasingPointer = AutoreleasingUnsafeMutablePointer<AnyClass>(buffer.baseAddress)
    objc_getClassList(autoreleasingPointer, allClassesCount)
}

然后,当我们找到符合Animal的类时,我们将其转换为适当的Swift类型((NSObject & Animal).Type),以便在实例化它时,获得适当类型的对象( NSObject & Animal):

for aClass in allClasses {
    if class_conformsToProtocol(aClass, Animal.self) {
        let animalClass = aClass as! (NSObject & Animal).Type

        // Because animalClass is `(NSObject & Animal).Type`:
        // - It has the `init()` of `NSObject`.
        // - Its instances are `NSObject & Animal`.
        let animal = animalClass.init()

        // Because animal is `NSObject & Animal`, it has the `noise` method of `Animal`.
        print(animal.noise())
    }
}

输出:

woof
meow

旁注。您可能认为可以避免这样做,从而避免使用class_conformsToProtocol

if let animalClass = aClass as? (NSObject & Animal).Type {
    let animal = animalClass.init()
    print(animal.noise())
}

但是您将在运行时崩溃:

*** CNZombie 3443: -[ conformsToProtocol:] sent to deallocated instance 0x7fffa9d265f0

在幕后,as?测试使用普通的Objective-C消息发送conformsToProtocol:消息给aClass。但是,系统框架中有多种“僵尸类”会在向其发送 any 消息时崩溃。这些类用于检测释放后使用错误。 class_conformsToProtocol函数不使用Objective-C消息传递,因此可以避免这些崩溃。