我正在创建一个包含 Swift CocoaPod 的 NativeScript 插件库。
在我的NativeScript plugin ,我正在使用一个单独的类来添加所需的 delegate到主类。
是否可以在主类中实现委托(delegate)方法并完全避免委托(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 中使用自委托(delegate)实现构造函数的正确语法
我当前的代码可以工作,但我正在寻求帮助,通过消除单独的委托(delegate)类来简化和减少代码。
最佳答案
当 TypeScript 转换为 Javascript 时,接口(interface)会丢失。因此,您需要使用 ObjCProtocols
静态字段并声明此类实现了哪些协议(protocol),例如:
export class MicrosoftBandService extends NSObject implements ConnectionDelegate {
public static ObjCProtocols = [ ConnectionDelegate ];
...
}
不会在 native 对象上调用第二个 TypeScript 构造函数(您可能会在控制台中看到有关此情况的警告)。
所以你应该执行 init
方法并在那里设置所有字段:
public static initWithOwner(band: MicrosoftBand): MicrosoftBandService {
let delegate = <MicrosoftBandService>MicrosoftBandService.new();
delegate._band = band;
band._delegate = delegate;
band.connectDelegate = delegate.
}
这里有几点需要注意:
避免 new() 重载。可能会导致某些 native 对象出现问题。
传递 band 实例,以便您可以在委托(delegate)方法中调用它(如果需要)
- 在乐队本地保留委托(delegate)的引用 - 大多数委托(delegate)都是作为弱引用实现的。如果你不保留对它的引用,那么没有人会保留它,并且它会在某个时候被 GC 收集。
有关协议(protocol)实现的更多信息可以在这里找到: http://docs.nativescript.org/runtimes/ios/how-to/ObjC-Subclassing
编辑: 应该可以做到:
export class MicrosoftBandService extends MicrosoftBand implements ConnectionDelegate
只要添加静态 ObjCProtocols
字段即可。然后您将不需要保留对委托(delegate)的引用,因为它将是同一个实例。 TypeScript 构造函数仍然不会被调用,因此您需要调用正确的 init
native 方法。
关于swift - 如何使用自委托(delegate)在 TypeScript 中实现 NativeScript 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41991160/