用于返回id <protocol> </protocol>的方法的Monotouch绑定

时间:2012-07-12 21:02:43

标签: xamarin.ios

我正在尝试绑定一个公开此方法的api(GoogleAnalytic v2 beta):

- (id<GAITracker>)trackerWithTrackingId:(NSString *)trackingId;

GAITracker是一个协议,所以我的绑定包含这个定义

[BaseType (typeof (NSObject))]
[Model]
interface GAITracker 
{
...
}

[BaseType (typeof (NSObject))]
interface GAI 
{
  [Static][Export ("sharedInstance")]
  GAI SharedInstance { get; }

  [Export("trackerWithTrackingId:")]
  GAITracker TrackerWithTrackingId(string id);

  ...
}

当我调用GAI.SharedInstance.TrackerWithTrackingId(“MyId”)时,我收到此异常

System.InvalidCastException: Unable to cast object of type 'MonoTouch.Foundation.NSObject' to type 'GoogleAnalyticBETA.GAITracker'.

我发现的所有示例都使用协议作为委托(as documented here),但不是作为方法的返回值。如何创建工作绑定?

1 个答案:

答案 0 :(得分:0)

你需要有这样的东西

[BaseType (typeof (NSObject))]
interface GAI 
{
  [Static][Export ("sharedInstance")]
  GAI SharedInstance { get; }

  [Export("trackerWithTrackingId:")]
  IntPtr TrackerWithTrackingId(string id);

  ...
}

然后使用它:

var ptr = GAI.SharedInstance.TrackerWithTrackingId("MyId");
var gaitracker = new GAITracker (ptr);

查看Google Analytic现有的monotouch绑定

https://github.com/mono/monotouch-bindings/blob/master/GoogleAnalytics/binding/googleanalytics.cs