MonoTouch异常没有被设备捕获

时间:2015-02-19 04:00:17

标签: ios xamarin.ios xamarin xamarin.android mvvmcross

我正在开发一个以前不使用Storyboard开发的应用程序,即所有视图都是在代码中创建的。因此,根据this链接,我正在尝试将自定义MvxTouchViewsContainer传递给MvxTouchSetup.CreateTouchViewsContainer

protected override IMvxTouchView CreateViewOfType(Type viewType, MvxViewModelRequest request)
    {

        UIStoryboard storyboard;

        try
        {

            storyboard = UIStoryboard.FromName(viewType.Name, null);
        }
        catch (Exception)
        {
            try {
                storyboard = UIStoryboard.FromName("MainStoryBoard_iPhone", null);
            }
            catch (Exception) {
                return base.CreateViewOfType (viewType, request);
            }
        }

        IMvxTouchView resultView = null;
        try {
             resultView = (IMvxTouchView) storyboard.InstantiateViewController(viewType.Name);

        } catch(Exception) {
            resultView = base.CreateViewOfType (viewType, request);

        }
        return resultView;
    }

基本上我试图找到一个故事板,如果存在,否则我回退到从代码加载视图。 try-catch异常在模拟器中工作正常。但是,在实际的iOS设备上运行并且应用程序崩溃时,异常不会被捕获。

我得到一个包含NSInvalidArgumentException的MonoTouch.Foundation.MonoTouchException,这基本上是预期的,因为某些视图可能没有与之关联的故事板。

这是一个Xamarin错误吗?

1 个答案:

答案 0 :(得分:3)

使用自定义属性比try / catch方法效果更好:

public class FromStoryboardAttribute : Attribute
{
    public string StoryboardName { get; set; }

    public FromStoryboardAttribute(string storyboardName = null)
    {
        StoryboardName = storyboardName;
    }
}

以下是StoryBoardContainer

public class StoryBoardContainer : MvxTouchViewsContainer
{
    protected override IMvxTouchView CreateViewOfType(Type viewType, MvxViewModelRequest request)
    {
        var storyboardAttribute = viewType.GetCustomAttribute<FromStoryboardAttribute>();
        if (storyboardAttribute != null) {
            var storyboard = UIStoryboard.FromName(storyboardAttribute.StoryboardName ?? viewType.Name, null);
            var viewController = storyboard.InstantiateViewController(viewType.Name);
            return (IMvxTouchView) viewController;
        }
        return base.CreateViewOfType(viewType, request);
    }
}

用法:

// Will look for a UIViewController with identifier "MyView" inside a Storyboard named "MyView.storyboard"
[FromStoryboard]
public class MyView : MvxViewController
{
    public MyView(IntPtr handle) : base(handle) {}
}

// Will look for a UIVIewController with identifier "MyOtherViewInSameStoryboard" inside a Storyboard named "MyView.storyboard"
[FromStoryboard(StoryboardName = "MyView")]
public class MyOtherViewInSameStoryboard : MvxViewController
{
    public MyOtherViewInSameStoryboard(IntPtr handle) : base(handle) {}
}