当我在iOS 9中使用Xcode 7.3时代码运行良好但是当我使用swift 3迁移到Xcode 8时,下面的代码向我显示运行时错误。仍然找到解决方案
class TableViewController: UITableViewController,NSFetchedResultsControllerDelegate,UISearchResultsUpdating {
var fetchResultController :NSFetchedResultsController<Restaurant>!
var searchController : UISearchController!
var searchResults :[Restaurant] = []
override func viewDidLoad() {
super.viewDidLoad()
let fetchRequest : NSFetchRequest<NSFetchRequestResult> = Restaurant.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
if let managedObjectContext = (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext{
fetchResultController = NSFetchedResultsController(fetchRequest: fetchRequest as! NSFetchRequest<Restaurant>, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
fetchResultController.delegate = self
do{
try fetchResultController.performFetch()
restaurants = fetchResultController.fetchedObjects!
}
catch{
print(error)
}
}
}
}
答案 0 :(得分:1)
从下面的代码我可以看到,你得到一个餐馆对象
var fetchResultController :NSFetchedResultsController<Restaurant>!
var searchController : UISearchController!
var searchResults :[Restaurant] = []
但是在你的fetchRequest中,你将它定义为NSFetchRequestResult。
let fetchRequest : NSFetchRequest<NSFetchRequestResult> = Restaurant.fetchRequest()
它可能是一个NSFetchRequestResult,但我建议你直接把它当作餐馆。我有一个类似的问题,这样做有效。试试这个,看看它是否有效。
let fetchRequest : NSFetchRequest<Restaurant> = Restaurant.fetchRequest()
答案 1 :(得分:-1)
试试这个:
<强> - &GT;转到应用代理
在 last 卷曲括号后输入:
let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistenceContainer.viewContext
<强> - &GT;返回TableViewController
删除if let
。
<强>类型:强>
var fetchResultController = NSFetchResultsController(
fetchRequest: Your fetchRequest,
manageObjectContext: context (From the delegate),
sectionNameKeyPath: nil, cacheName: nil
)
self.fetchResultController = fetchResultController