Skip to main content
 首页 » 编程设计

c#之在 MonoTouch : works, 中绑定(bind) native 库,但为什么子类化时会出现奇怪的结果缺少 NullAllowed 属性

2024年02月20日12linjiqin

单点触控 5.2.13

我正在通过 MonoTouch 绑定(bind)使用 native ObjectiveC 库。该库公开了一个 View Controller 。一切正常,直到我将 View Controller 子类化。然后,我得到 NULL 引用异常或部分 UI 未显示。

我已经阅读了有关 btouch 工具和“-e”选项的问题。但据我所知,该选项不存在:

Tool /Developer/MonoTouch/usr/bin/btouch execution started with arguments: /d:DEBUG ApiDefinition.cs /s:StructsAndEnums.cs /tmpdir:obj/Debug/ios/ /sourceonly:obj/Debug/ios//sources.list

子类(在这个例子中)没有添加任何功能,但使用它足以打破绑定(bind):

// Works. 
var contr = new NativeController(); 
 
// Fails with various errors. Throws a NULL reference exception about some UIPopoverController being NULL, for instance. 
public class SubclassedController : NativeController 
{ 
  public SubclassedController() : base() 
  { 
  } 
} 
 
var contr = new SubclassedController(); 

我发现将 [NullAllowed] 添加到属性可以解决 NULL 引用异常。

native Controller 公开属性 (nonatomic, strong) UIPopoverController *popoverController。这被绑定(bind)为 UIPopoverController PopoveController {get; set;} - 在此处添加 NullAllowed 解决了问题。

但现在我面临着图像不显示的问题,并且没有明显的异常。

我假设这些问题也源于这样一个事实,即使用子类版本时某些东西为 NULL,但 native 代码似乎对 NULL 使用react并优雅地处理它。

这引出了三个问题:

  • 为什么使用子类时行为不同? MonoTouch 正在做什么来实现这一目标?为什么在我使用派生类的情况下得到 NULL ref?无论哪种情况,我都不会触及 UIPopoverController。
  • 如果没有错误,我如何找出问题所在以及如何解决?
  • 除了 NullAllowed,还有什么需要注意的?

请您参考如下方法:

Why is the behavior different when using subclassing?

可能有多种原因,包括实例根据其类名以不同方式初始化自身。这在 C#(非常不常见,使用的是继承)或 Objective-C(委托(delegate)通常用于自定义行为)中并不难。

您需要引用 documentation , header files , samples和您的原生库的产品支持,以了解子类化的工作原理。

What is MonoTouch doing to make this happen?

我认为它与 MonoTouch 无关。 MonoTouch 提供 btouch 来帮助您为 Objective-C 库创建绑定(bind)。这是 Xamarin 用于进行所有 iOS 绑定(bind)的相同工具。

还是不确定?写一个小的 Objective-C 示例来做同样的事情。将结果与 MonoTouch 版本进行比较。

不同的结果?填一个bug report使用(C# 和 ObjC)测试用例,我们将检查发生了什么(如前所述,我们有充分的理由确保 btouch 没有错误 ;-)

Why do I get a NULL ref in the case I use a derived class? I'm not touching the UIPopoverController an either case.

How can I find out what is wrong and how to fix it if there is no error?

What else has to be taken care of, besides the NullAllowed?

在这个阶段,您正在运行您绑定(bind)的库的 native 代码。您需要遵循的特定规则是您可以通过以下方式找到的规则:

  • 阅读图书馆文档;
  • 阅读库源代码(如果可用)、标题和示例;
  • 对于[NullAllowed],您可以测试(例如单元测试)是否允许null(例如它会崩溃);

同时移植现有示例既是一个很好的学习练习(库 API),也是测试绑定(bind)错误(例如选择器中的拼写错误、错误参数...)的快速方法。