Fatal error : unexpectedly found nil - number of row
Fatal error : unexpectedly found nil - number of row
我的 UITableViewController 工作正常,直到最近它在初始加载时在 tableview 的 numberOfRowsInSection 崩溃。
通过以下方法获取数据源:
func reloadTheTable()
{
datasource = PlaceDataController.fetchAllPlaces()
tableView?.reloadData()
}
我的Realm模型中的方法是:
class func fetchAllPlaces() -> Results<PlaceItem>!
{
do
{
let realm = try Realm()
return realm.objects(PlaceItem)
}
catch
{
return nil
}
}
如何调试这个错误?之前工作正常。真的很奇怪为什么它现在崩溃了。
我猜 datasource
是一个根据 fetchAllPlaces
return 类型的隐式解包选项。
首先,fetchAllPlaces
不应该 return 一个隐式展开的可选值,因为您知道值可以是 nil
,将其替换为:
class func fetchAllPlaces() -> Results<PlaceItem>?
{
do
{
let realm = try Realm()
return realm.objects(PlaceItem)
}
catch
{
return nil
}
}
此外,声明您的 datasource
为可选。
然后替换你的numberOfRowsInSection
方法:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let dataSource = datasource {
return dataSource.count
}
return 0
}
我的 UITableViewController 工作正常,直到最近它在初始加载时在 tableview 的 numberOfRowsInSection 崩溃。
通过以下方法获取数据源:
func reloadTheTable()
{
datasource = PlaceDataController.fetchAllPlaces()
tableView?.reloadData()
}
我的Realm模型中的方法是:
class func fetchAllPlaces() -> Results<PlaceItem>!
{
do
{
let realm = try Realm()
return realm.objects(PlaceItem)
}
catch
{
return nil
}
}
如何调试这个错误?之前工作正常。真的很奇怪为什么它现在崩溃了。
我猜 datasource
是一个根据 fetchAllPlaces
return 类型的隐式解包选项。
首先,fetchAllPlaces
不应该 return 一个隐式展开的可选值,因为您知道值可以是 nil
,将其替换为:
class func fetchAllPlaces() -> Results<PlaceItem>?
{
do
{
let realm = try Realm()
return realm.objects(PlaceItem)
}
catch
{
return nil
}
}
此外,声明您的 datasource
为可选。
然后替换你的numberOfRowsInSection
方法:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let dataSource = datasource {
return dataSource.count
}
return 0
}