eventsxamarinxamarin.iosweak-referencesxamarin.ios-binding

Xamarin binding Events WeakDelegate issue


I have following

iOS code:

@protocol TestDelegate

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

@end

@interface Utility : NSObject

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

@end

and Sharpie generated code with delegate to event mapping:

[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; }
}

When I'm attaching only to the events and not using delegate property then events are not fired.

Correct me if I’m wrong but when using only events then nothing is referring to the internally created _XDelegate so it will be garbage collected right away.

In my case I had to store internal _XDelegate after attaching to the events to make them work.

public class TestClass
{
    private readonly Delegate _del;

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

Solution

  • The issue was somewhere else - SingletonInstance() is a method instead of property so nothing is referring to the returned object so it's being GCed.