在Swift 3.0之前,我们可以这样fetch数据:
var people = [NSManageObject]()
//1
let fetchRequest = NSFetchRequest(entityName: "Person")
do {
//2
let results =
try managedContext.executeFetchRequest(fetchRequest)
//3
people = results as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error),\(error.userInfo)")
}
}
不过在Swift 3.0以后,要做一些调整,首先第1句修改为:
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
在这里你必须明确指定一种泛型,在第2句修改如下:
let results = try managedContext.fetch(fetchRequest)
最后第3句不需要做改变.
其实第1句也可以这么写:
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person")
这样第3句就可以将类型转换删掉了:
people = results