【问题标题】:gomobile: binding callbacks for ObjCgomobile:绑定 ObjC 的回调
【发布时间】:2018-06-12 11:07:03
【问题描述】:

我有一个 Go 界面

type GetResponse interface { OnResult(json string) }

我必须使用此接口从 ObjC 订阅 OnResult 事件。

func Subscribe( response GetResponse){ response.OnResult("some json") }

ObjC 绑定给了我一个对应的协议和一个基础类

@interface GetResponse : NSObject <goSeqRefInterface, GetResponse> {
}
@property(strong, readonly) id _ref;

- (instancetype)initWithRef:(id)ref;
- (void)onResult:(NSString*)json;
@end

所以,我需要在我的 ObjC 环境中获取这个 json。我该怎么做?

  1. 子类化 如果我将此 GetResponse 子类化或直接使用它并传递给订阅例程,它会崩溃 '不允许在objective-c 对象上使用go_seq_go_to_refnum'
  2. 类别如果我在 Go 端创建带有协议支持的结构,我不能子类化它,但至少它不会崩溃:

    type GetResponseStruct struct{}
    func (GetResponseStruct) OnResult(json string){log.Info("GO RESULT")}
    func CreateGetResponse() *GetResponseStruct{ return &GetResponseStruct{}}
    

    我有一个实体对象,没有明显的方法来连接我的回调。如果我创建一个类别并覆盖 onResult 例程,则不会调用它。仅仅因为覆盖现有的类方法不是根据 AppleDoc 确定的行为。任何时候从 Go 调用 OnResult,都会调用默认实现并出现“GO RESULT”。

  3. Swizzling我尝试使用 category 和 swizzle(用我重命名的方法替换方法的实现),但它只有在我从 ObjC env 调用 onResult 时才有效。

有什么办法可以解决我的问题吗?或者我只是不很准确地红色文档?请帮帮我

【问题讨论】:

    标签: ios objective-c go gomobile


    【解决方案1】:

    我今天遇到了类似的问题。我认为这是 gomobile 中的一个错误,但毕竟这是我对 swift/objc 的误解。 https://github.com/golang/go/issues/35003

    该错误的 TLDR 是您必须子类化协议,而不是接口。如果您使用的是 swift,那么您可以将 GetResponseProtocol 子类化:

    class MyResponse: GetResponseProtocol
    

    如果在 objc 中,那么您可能希望直接实现 GetResponse 协议,而不是对接口进行子类化。

    【讨论】:

      猜你喜欢
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      • 2019-04-06
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多