Xamarin绑定事件WeakDelegate问题

时间:2017-06-23 13:30:26

标签: events xamarin xamarin.ios weak-references xamarin.ios-binding

我有以下

iOS代码:

@protocol TestDelegate

- (void)onSuccess:(NSString*)token;

@end

@interface Utility : NSObject

@property (nullable, weak, getter = getTestDelegate, setter = setTestDelegate:) id<TestDelegate> delegate;

@end

和Sharpie使用委托生成代码到事件映射:

[Protocol, Model]
public interface TestDelegate
{
    [Export ("onSuccess:")]
    void OnSuccess (string token);
}

[BaseType(typeof(NSObject),
      Delegates = new string[] { "WeakDelegate" },
      Events = new Type[] { typeof(TestDelegate) })
public interface Utility
{
    [Wrap ("WeakDelegate")]
    [NullAllowed]
    TestDelegate Delegate { [Bind ("getTestDelegate")] get; [Bind ("setTestDelegate:")] set; }

    [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
    NSObject WeakDelegate { [Bind ("getTestDelegate")] get; [Bind ("getTestDelegate:")] set; }
}

当我只附加事件而不使用委托属性时,不会触发事件。

如果我错了,请纠正我,但是当只使用事件时,没有任何东西指的是内部创建的_XDelegate,所以它会立即被垃圾收集。

在我的情况下,我必须在附加到事件后存储内部_XDelegate以使它们工作。

public class TestClass
{
    private readonly Delegate _del;

    public TestClass()
    {
        iOS.SingletonInstance().OnSuccess += HandleOnSuccess;
        _del = iOS.SingletonInstance().Delegate; //store Delegate instance to make events work
    }
}

1 个答案:

答案 0 :(得分:0)

问题出在其他地方 - SingletonInstance()是一个方法而不是属性,因此没有任何东西引用返回的对象,所以它被GCed。