How to bind Objective-C initXXX method to Xamarin.iOS’s constructor, which has same types of arguments?


In Objective-C, sometimes there are multiple initXXX methods which have same type of arguments. For example,

    -(id)initWithImageArray:(NSArray *)images;

    -(id)initWithPNGorJPEGDataArray:(NSArray *)data;

If we prepare to bind it to Xamarin.iOS by Objective Sharpie, OS creates such template:

    // -(id)initWithImageArray:(NSArray *)images;
    [Export ("initWithImageArray:")]
    IntPtr Constructor (NSObject [] images);

    // -(id)initWithPNGorJPEGDataArray:(NSArray *)data;
    [Export ("initWithPNGorJPEGDataArray:")]
    IntPtr Constructor (NSObject [] data);

But these c# interfaces are same, so it cannot compile successfully.

Are there any strategy to bind such type of Objective-C libraries?

Thanks, Ko-hei


There are a few ways. The simplest is to figure out (from the documentation of your library) what’s the type used inside the NSArray.

E.g. if the first case is documented as an array of UIImage and the second was documented as a array of NSData

-(id)initWithImageArray:(NSArray *)images; // array of UIImage
-(id)initWithPNGorJPEGDataArray:(NSArray *)data; // array of NSData

Then it can be bound as

IntPtr Constructor (UIImage [] images);

IntPtr Constructor (NSData [] data);

That would give both constructors different signatures, compile correctly and make a better binding (as it would be more typesafe than using NSObject).

Answered By – poupou

Leave a Comment