Ошибка при запуске приложения: Foundation.MonoTouchException: создано исключение Objective-C (Xamarin iOS)

Я получаю это сообщение об ошибке при запуске моего приложения:

Foundation.MonoTouchException: создано исключение Objective-C. Имя: NSInvalidArgumentException Причина: -[TableSource initWithCoder:]: нераспознанный селектор отправлен экземпляру 0x796e6fa0

Я уже искал в гугле, но не нашел решения.

О приложении: Приложение имеет UITableView с некоторыми пользовательскими ячейками. UITableView находится в обычном «представлении». В обычном «представлении» также есть кнопка, эта кнопка должна (при касании) добавлять пользовательскую ячейку в UITableView.

UITableView имеет имя «tableView» и свойства класса «TableSource». Кнопка имеет имя "btn01" и в свойствах как класс "ViewController".

Пользовательские ячейки имеют «идентификатор повторного использования» «Cell01Reuse», «Cell02Reuse» и т. д. И класс «Testclass» (который не существует в виде файла).

Контроллер представления (база, на которой все включено) имеет класс «ViewController».

У меня есть два класса с кодом. Во-первых, это «Контроллер просмотра»:

using System;
using UIKit;
using Foundation;
using System.Collections.Generic;

namespace myapp
{
    public partial class ViewController : UIViewController
    {
        public ViewController(IntPtr handle) : base(handle)
        {
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Perform any additional setup after loading the view, typically from a nib.

            //UITableView _table;
            //_table = new UITableView
            //{
            //    Frame = new CoreGraphics.CGRect(0, View.Bounds.Height * 0.03, View.Bounds.Width, View.Bounds.Height * 0.80),
            //    Source = new TableSource(null)
            //};
            //_table.SeparatorStyle = UITableViewCellSeparatorStyle.None;
            //View.AddSubview(_table);

            TableSource TS = new TableSource();

            btn01.TouchUpInside += (sender, e) =>
            {
                TS.updateTableView();
                string cell01 = "Cell01Reuse";
                TS.tableItems.Add(cell01);
            };
        }

        public override void DidReceiveMemoryWarning()
        {
            base.DidReceiveMemoryWarning();
            // Release any cached data, images, etc that aren't in use.
        }
    }
}

Во-вторых, "TableSource":

using System;
using System.Collections.Generic;
using System.Text;
using Foundation;
using UIKit;

namespace myapp
{
    public partial class TableSource : UITableViewSource
    {



        //string[] tableItems;
        public List<string> tableItems = new List<string>();
        public static string cellIdentifier = "TableCell";

        //public TableSource(string[] items)
        //{
        //    tableItems = items;
        //}

        public TableSource()
        {
        }

        public override nint RowsInSection(UITableView tableview, nint section)
        {
            return 0;
        }

        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier);
            if (cell == null)
            {
                cell = new UITableViewCell(UITableViewCellStyle.Default, cellIdentifier);
            }
            cell.TextLabel.Text = tableItems[indexPath.Row];
            tableItems.Add(Convert.ToString(cell));
            return cell;
        }

        public override nint NumberOfSections(UITableView tableView)
        {
            return base.NumberOfSections(tableView);
        }

        public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            new UIAlertView("Alert", "You touched: " + tableItems[indexPath.Row], null, "OK", null).Show();
            tableView.DeselectRow(indexPath, true);
        }

        public void updateTableView()
        {
            tableView.updateTableView();
        }
    }
}

person Reaper    schedule 27.07.2016    source источник


Ответы (1)


На самом деле я не могу воспроизвести проблему, с которой вы столкнулись, ваше описание недостаточно ясно, но в вашем коде наверняка есть какая-то проблема, например, вы не должны возвращать 0 в методе RowsInSection, я могу дать вам образец для справки. ( Весь пользовательский интерфейс создается кодом)

public partial class ViewController : UIViewController
{
    protected ViewController (IntPtr handle) : base (handle)
    {
        // Note: this .ctor should not contain any initialization logic.
    }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        // Perform any additional setup after loading the view, typically from a nib.

        CGRect tableFrame = this.View.Bounds;
        tableFrame.Y = 100;
        tableFrame.Height -= 100;
        UITableView tableView = new UITableView (tableFrame);
        this.View.AddSubview (tableView);

        MyTalbeSource mySource = new MyTalbeSource ();
        tableView.Source = mySource;
        tableView.ReloadData ();

        int count = 0;
        UIButton btnNew = new UIButton (UIButtonType.System);
        btnNew.Frame = new CGRect (20, 20, 100, 40);
        btnNew.SetTitle ("NewItem", UIControlState.Normal);
        btnNew.TouchUpInside += delegate {
            mySource.AddNewItem ("NewItem" + count++);
            tableView.ReloadData ();
        };
        this.Add (btnNew);
    }
}

class MyTalbeSource : UITableViewSource
{
    private const string CELL_ID = "MyTalbeCell";
    private List<string> dataList;

    public MyTalbeSource ()
    {
        dataList = new List<string> ();
        for (int i = 0; i < 5; i++) {
            dataList.Add ("Test " + i.ToString ());
        }
    }

    public void AddNewItem (string title)
    {
        dataList.Add (title);
    }

    public override nint RowsInSection (UITableView tableview, nint section)
    {
        return dataList.Count;
    }

    public override UITableViewCell GetCell (UITableView tableView, Foundation.NSIndexPath indexPath)
    {
        MyTableCell cell = tableView.DequeueReusableCell (CELL_ID) as MyTableCell;
        if (null == cell) {
            cell = new MyTableCell (UITableViewCellStyle.Default, CELL_ID);
            cell.InitCell ();
        }
        cell.Text = dataList [indexPath.Row];
        return cell;
    }
}

class MyTableCell : UITableViewCell
{
    private UILabel lbInfo;

    public string Text { 
        get {
            return lbInfo.Text;
        }
        set {
            lbInfo.Text = value;
        }
    }

    public MyTableCell (UITableViewCellStyle style, string cellID) : base (style, cellID)
    {
    }

    public void InitCell ()
    {
        lbInfo = new UILabel ();
        lbInfo.TextAlignment = UITextAlignment.Center;
        this.AddSubview (lbInfo);
    }

    public override void LayoutSubviews ()
    {
        lbInfo.Frame = this.Bounds;
    }
}

Надеюсь, это поможет вам.

Приветствуются любые вопросы о Xamarin.iOS.

person Alanc Liu    schedule 27.07.2016
comment
Немного помогает, но не решает мою проблему. Я не знаю, как лучше описать мою ситуацию, как описано выше. Но спасибо! - person Reaper; 27.07.2016
comment
Можете ли вы поделиться своим решением где-нибудь? Или дайте мне более подробную информацию, чтобы помочь вам. Кстати, вы не должны делать UITableView свойством в вашем UITableSource. - person Alanc Liu; 28.07.2016
comment
Еще раз спасибо за ответ. Мне удалось найти другой способ решить мою задачу. Я использовал пример из Xamarin и построил вокруг него. Вот пример: developer.xamarin.com/recipes/ios/content_controls /tables/ На данный момент у меня больше нет проблемы. Есть ли способ как-то сообщить вам, если я снова столкнусь с этой проблемой (или похожей) снова? Потому что вы, кажется, знаете о Xamarin. Еще раз спасибо за ваши усилия! PS: я отметил ваш пост как ответ, потому что, если бы у меня все еще была проблема, вы бы помогли мне ее решить. - person Reaper; 28.07.2016
comment
Очень рад узнать, что вы решили свою проблему, если у вас есть какие-то вопросы, просто задайте их здесь. Я не уверен, разрешил ли стек пользователю оставить свою контактную информацию. - person Alanc Liu; 29.07.2016