CoreData在Swift 3.0中的一点改变

来源:互联网 发布:java 发送短信接口 编辑:程序博客网 时间:2024/06/08 03:59

在Swift 2.0中我们需要从core data中query结果的时候使用的是如下方式:

func findAnimals() {    let request = NSFetchRequest(entityName:”Animal")        do {        guard let searchResults = try context.executeFetchRequest(request) as? [Animal] else {        print("Results were not of the expected structure")        }        ... use(searchResults) ...        } catch {        print("Error ocurred during execution: \(error)")    }}

注意,以上代码试图将executeFetchRequest返回的结果转换为实际数据类型的数组。同时我们看到,在建立request的时候直接使用的是NSFetchRequest的纯构造器方式。

但是在Swift 3.0中首先我们在创建request的时候必须用范型来指定实际数据类型,你可以用如下任何一句来完成:

let fetch0 = NSFetchRequest<Commit>(entityName: "Commit")let fetch1:NSFetchRequest<Commit> = Commit.fetchRequest()

接下来在处理fetch结果的时候我们不可以将NSFetchRequestResult直接转换为[Commit],因为这样非相关性的转换总是失败!作为代替我们使用context的另一个方法来完成:

do{            let commits = try managedObjectContext.fetch(fetch)            print("***** \(commits.count) commits *****")            objects = commits            tableView.reloadData()        }catch let error{            print("Fetch failed : \(error.localizedDescription)")        }

that‘s all,good luck! ;)

0 0