initialize swift class from objective c library
Hello I am currently importing a project from objective C to swift. The objective C project uses a custom library which in one of the classes it has a function that takes a Class object, which, when the data is loaded it initializes an id obj with the class(code below). On the objective C side this works great! I am using the same library on swift with a bridge header but unfortunately my object is nil once the data is loaded. I verified the data object used to initialize the object has content. The custom swift class also requires me to implement an init(data: Data) initializer when I add a custom init(), I am new to swift any help would be great! Thank you!
Objective C:
Library:
-(id) buildRetObject:(Class)clss fromData(NSData*) data{
id obj = nil;
if (data != nil) {
obj = [[clss alloc] initWithData:data];
}
}
Custom Object, is a subclass of another custom object, not in library but on main app:
Item.m:
-(id)init{
if ([super init]){
//do something
}
return self
}
Same Item object in swift:
//customClass super class is abstactCustomClass which is a sub abstract class of NSObject class, init functions are in here, the abstract class
class Item: customClass {
//variables
override init() {
super.init()
// do something
}
required init!(data: Data){
//fatalError(message here)
/*tried calling supers method
super.init(data:Data) gives error: fatal error: use of unimplemented initializer 'init(dictionary:)'*/
}
//methods
}
After a lot of digging I was finally able to figure it out, objective C knows from the abstract class what the initializers are, swift doesn't. So all I need to do was implement this initializers and it works.
required init!(data: Data){
super.init(data:Data)
}
override init(dictionary: [AnyHashable: Any]!){
super.init(Dictionary:dictionary)
}
链接地址: http://www.djcxy.com/p/66182.html
下一篇: 从目标C库初始化Swift类