我具有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”的子类提供。
有没有办法获取“猫”和“狗”的实例?
答案 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消息传递,因此可以避免这些崩溃。