Greag.Deay Greag.Deay - 5 months ago 41
iOS Question

Xamarin iOS UITableView, How to delete first row?

I've implemented chat in my application with a limit of 100 messages, because of perfomance, and suddenly I found, that rows editing is not that easy, as I expected.
So I tried this:

public void RemoveTopRow()
{
messages.RemoveAt (0);
tableView.ReloadData ();
}


But it crashed with native exception, I didn't stop here and tried this one:

tableView.DeleteRows (new NSIndexPath[]{ NSIndexPath.FromItemSection(0,0) }, UITableViewRowAnimation.Fade);


But, same result: native crash
enter image description here

Maybe someone knows how to do this? Little working code sample will be so helpful, I promise, on my next vacation, I'll do some refactoring and publish this chat client on github, so others will be able to implement it in their projects without UI pain, because I've spent too much time and nerves on those layout fixes

Answer

Without seeing where you calling your RemoveTopRow method, I can only guess, but from the error, I'm assuming you are in the middle of adding a new chat row and are deleting the first one from your FIFO stack before the tableview/datasource is finished syncing:

        public void RemoveTopRow()
        {
            dataSource.Objects.RemoveAt (0);
            TableView.ReloadData ();
        }

        void AddNewItem (object sender, EventArgs args)
        {
            dataSource.Objects.Add (DateTime.Now);

            // This will cause the error that you are seeing when 
            //  it reaches the TableView.InsertRows...
            //if (dataSource.Objects.Count > 10) {
            //  RemoveTopRow ();
            //}

            using (var indexPath = NSIndexPath.FromRowSection (0, 0))
                TableView.InsertRows (new [] { indexPath }, UITableViewRowAnimation.Automatic);

            //This will work
            if (dataSource.Objects.Count > 10) {
                RemoveTopRow ();
            }
        }