3

我在执行下面的代码时收到此错误

未能创建本机类型“ NSObject ”的实例,可以通过将 Class.ThrowOnInitFailure 设置为 false 来忽略此条件

    var alert=new UIAlertView("Error","Something missing !"
                              ,new UIAlertViewDelegate(),"OK",null);

我仅在最新的 iOS 6 模拟器中收到此错误。对于我的 iOS 5 设备,它按预期工作。

4

2 回答 2

6

This is because of a recent modification to Xamarin.iOS.

Traditionally MonoTouch has allowed managed objects to be created without a native peer. The behavior has however been inconsistent between types, and in the case of types from third-party libraries it would result in instances which would, if used, most likely crash the process with a stack overflow. So the default behavior has been changed: an exception will be thrown if a native peer cannot be created for a managed object. As the exception message also mentions this behavior is controlled by the value MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure - set it to false to return to the old behavior.

In your case you get the exception because you're trying to create a UIAlertViewDelegate instance when there is no corresponding Objective-C class (since UIAlertViewDelegate is an Objective-C protocol, not an Objective-C class).

The solution is simple, as user1010710 already mentioned, just use null instead of new UIAlertViewDelegate(). The result is identical: in previous versions of Xamarin.iOS you would end up with a managed UIAlertViewDelegate instance whose Handle is IntPtr.Zero - and that IntPtr.Zero value would be passed to the native constructor. This is exactly what happens when you pass null.

于 2013-03-20T13:28:36.213 回答
1

尝试这个:

var alert = new UIAlertView ("Error", "Something missing !", null, "OK");
于 2013-03-20T11:49:02.683 回答