Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin binding objective-c library to C# delegates and events

This is a follow up from my last question about binding objective-c library to xamarin project. So I figured that I will create the api definition my self, but I cannot figure out how to rewrite objective-c delegates to C# delegates/events. I've come to the understanding that objective-c delegates is not the same as C# delegates, but more like C# events.

This is the objective-c delegate definition (from the header file):

@protocol LineaDelegate
@optional

-(void)connectionState:(int)state;

@end

This is the objective-c class definition (from the header file):

@interface Linea : NSObject

-(void)connect;

@end

The connect method works in background and will notify the caller of connection success via connectionState delegate.

Now, how do I bind the api correctly? This is my ApiDefinition.cs so far:

[BaseType(typeof(NSObject))]
interface Linea{
     [Export ("isPresent")]
     bool IsPresent();

     //the delegate that will be notified of Linea events
     [Export("addDelegate:")]
     void AddDelegate (NSObject newDelegate);

     [Export("connect")]
     void Connect ();
}

How can I convert the objective-c delegate into something useful in Xamarin studio and C#?

like image 393
Karoline Brynildsen Avatar asked Aug 21 '13 11:08

Karoline Brynildsen


1 Answers

Now, the minute I post a question here I figure out the solution by my self... I post the solution here not only for my own reference, but also for others out there who will struggle with the same issue.

I found this tutorial (see chapter 4.3) and figured I had to use weak delegates. Working like a charm!

like image 98
Karoline Brynildsen Avatar answered Sep 30 '22 15:09

Karoline Brynildsen