您当前的位置: 首页 >  swift

CoreData在Swift 3.0中的一点改变

发布时间:2016-11-09 19:39:37 ,浏览量:0

在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(entityName: "Commit") let fetch1:NSFetchRequest= 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! ;)

关注
打赏
1688896170
查看更多评论

暂无认证

  • 0浏览

    0关注

    107766博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0729s