我正在创建一个包装Swift CocoaPod lib。
的NativeScript插件在我的NativeScript plugin中,我使用单独的类向主要类添加必需的delegate。
是否可以在主类中实现委托方法并完全避免委托类?
即,
export class MicrosoftBandService extends NSObject implements ConnectionDelegate {
static new(): MicrosoftBandService {
return <MicrosoftBandService>super.new()
}
constructor() {
let _self= this;
this.mbk = MicrosoftBand.alloc().init();
this.mbk.connectDelegate = _self
}
onConnecte() {
//
onDisconnecte() {
//
}
onErrorWithError(error) {
//
}
}
更好,我喜欢这样做
export class MicrosoftBandService extends MicrosoftBand implements ConnectionDelegate {
static new(): MicrosoftBandService {
return <MicrosoftBandService>super.new()
}
constructor() {
let _self= this;
this.connectDelegate = _self
}
onConnecte() {
//
}
onDisconnecte() {
//
}
onErrorWithError(error) {
//
}
}
我不知道在TypeScript for NativeScript中用self delegate实现构造函数的正确语法
我当前的代码有效,但我正在寻求帮助,通过消除单独的委托类来简化和减少代码。
答案 0 :(得分:3)
当TypeScript转换为Javascript时,接口丢失。因此,您需要使用ObjCProtocols
静态字段并声明此类实现的协议,如:
export class MicrosoftBandService extends NSObject implements ConnectionDelegate {
public static ObjCProtocols = [ ConnectionDelegate ];
...
}
第二个TypeScript构造函数不会在本机对象上调用(您可能在控制台中有关于此的警告)。
所以你应该做init
方法并在那里设置所有字段:
public static initWithOwner(band: MicrosoftBand): MicrosoftBandService {
let delegate = <MicrosoftBandService>MicrosoftBandService.new();
delegate._band = band;
band._delegate = delegate;
band.connectDelegate = delegate.
}
这里有几点需要注意:
避免new()重载。可能会导致某些原生对象出现问题。
传递band实例,以便您可以在委托方法中调用它(如果需要)
有关协议实施的更多信息,请访问: http://docs.nativescript.org/runtimes/ios/how-to/ObjC-Subclassing
编辑: 应该可以这样做:
export class MicrosoftBandService extends MicrosoftBand implements ConnectionDelegate
只要添加静态ObjCProtocols
字段即可。然后,您将不需要保留对委托的引用,因为它将是同一个实例。仍然不会调用TypeScript构造函数,因此您需要调用正确的init
本机方法。