Xamarin在iOS中使用自定义UITableViewCell时抛出NullReferenceException

我有一个非常类似的问题,在Xamarin自定义UITableViewCell抛出系统NullReferenceException讨论的问题。

尽pipe如此,在回答问题之后,我的问题还没有解决。

我有一个自定义的UITableView BoardListCell 。 在我的故事板,我有一个UITableView 。 它可以在我的ViewController通过socketstableView

在我的视图控制器,我得到的数据。 然后我做tableView.Source = new BoardsTableViewSource(sourceData);

我的BoardsTableViewSource

 using System; using System.Collections.Generic; using Foundation; using UIKit; public class BoardsTableViewSource : UITableViewSource { private List<List<Object>> data; Boolean normalBoards; public BoardsTableViewSource (List<List<Object>> data, bool normalBoards) { this.data = data; this.normalBoards = normalBoards; } public List<List<Object>> getData() { return data; } public override nint RowsInSection (UITableView tableview, nint section) { return data.Count; } public override string TitleForHeader (UITableView tableView, nint section) { return "Header"; } public override string TitleForFooter (UITableView tableView, nint section) { return "Footer"; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { BoardListCell cell = (BoardListCell)tableView.DequeueReusableCell("BoardTableCell"); List<Object> cellData = data [indexPath.Row]; cell.setData("1","!"); //I have simplified the data for this example } } } 

debugging时,我得到cell.setData()行的NullReferenceexception。

在StoryBoard中,我将BoardListCell的标识符设置为BoardTableCell

BoardListCell

 public partial class BoardListCell : UITableViewCell { public static readonly UINib Nib = UINib.FromName ("BoardListCell", NSBundle.MainBundle); public static readonly NSString Key = new NSString ("BoardListCell"); public BoardListCell() : base() { } public BoardListCell (IntPtr handle) : base (handle) { } public static BoardListCell Create () { return (BoardListCell)Nib.Instantiate (null, null) [0]; } public void setData(String top, String bottom) { this.exp.Text = top; this.playTime.Text = bottom; } } 

expplayTimeUILabel的出口。 我已经删除并重新添加了网点,但这并没有改变任何东西。

我不知道问题是什么。 我唯一能想到的是因为我正在使用我用StoryBoard制作的UITableView ,并通过sockets访问它。 不过,我不知道问题是什么…

如果DequeueReusableCell找不到合适的单元格来重用,则DequeueReusableCell将返回null。 所以你需要在引用你的单元之前明确地检查一下:

 BoardListCell cell = (BoardListCell)tableView.DequeueReusableCell("BoardTableCell"); if (cell == null) { cell = new BoardListCell(); }