CoreData - 检查数据库中是否存在对象

时间:2016-06-22 15:55:18

标签: ios core-data

我有viewController和表视图以及FetchResultsController。 ViewController从Web下载数据,然后将其保存到CoreData。每次发布都会发生下载。我需要一些比较我从网上下载的信息,只保存到CoreData

我该怎么做?

我有一个想法是通过fetchedResultsController.performFetch()获取所有对象,然后将它们分配给数组,但我不明白如何迭代该数组(我们[AnyObject])

也许有更简单的方法?

2 个答案:

答案 0 :(得分:2)

我想出了

我需要执行几个步骤,以便将核心内容与自定义对象数组进行比较

1)创建空数组

var arrayOfReposOnDisk : [RepoObject] = []

2)从CoreData获取对象

let fetchedData = self.fetchedResultsController.fetchedObjects

3)迭代fetchedData并将键值的每个值转换为我的自定义对象

for i in 0 ..< fetchedData!.count  {

        let object = fetchedData![i]

        let name = object.valueForKey("name") as! String
        let description = object.valueForKey("description") as! String
        let authorName = object.valueForKey("avatarURL") as! String
        let avatarURL = object.valueForKey("authorName") as! String
        let forks = object.valueForKey("forks") as! Int
        let watches = object.valueForKey("watches") as! Int

        let repoObject = RepoObject(name: name, description: description, authorName: authorName, avatarURL: avatarURL, forks: forks, watches: watches)

        arrayOfItemsOnDisk.append(repoObject)
    }

4)最后,进行比较

if arrayOfReposOnDisk.contains ({ $0.name == name }) {
       print("There is the same name in json as in CoreData, doing nothing")
   } else {
       self.insertNewObject(name, descriptionText: description, avatarURL: avatarURL, authorName: authorName, forks: forks, watches: watches)
}

答案 1 :(得分:0)

您可以在获取的结果控制器上使用fetchedObjects。它是[AnyObject]?的数组,但您可以使用类似

的类型将其强制转换为对象类型
if let myObjects = fetchedResultsController.fetchedObjects as? [MyObjectType] {
    for object in myObjects {
        // do some comparison to see if the object is in your downloaded data
    }
}

获取对象的另一种方法是在托管对象上下文中创建NSFetchRequest并使用executeFetchRequest