Alexey K
Alexey K

Reputation: 6723

CoreData - check if object exists in database

I have viewController with table view and FetchResultsController. ViewController downloads data from web and then save it to CoreData. Downloading happens every launch. I need someway to compare info that I downloaded from web and only the save it to CoreData

How can I do this ?

I had an idea of fetching all objects by fetchedResultsController.performFetch() and then assigning them to array, but I dont understand how to iterate over that array (it us [AnyObject])

Maybe there are more easy ways ?

Upvotes: 1

Views: 1712

Answers (2)

Alexey K
Alexey K

Reputation: 6723

I figured that out

I need to perform several steps in order to make comparison of content from core with array of custom objects

1) create empty array

var arrayOfReposOnDisk : [RepoObject] = []

2) fetch objects from CoreData

let fetchedData = self.fetchedResultsController.fetchedObjects

3) iterate over fetchedData and convert each value for key-value to my custom object

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) finally, make a comparison

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)
}

Upvotes: 2

Russell Austin
Russell Austin

Reputation: 409

You can used fetchedObjects on the fetched results controller. It is an array of [AnyObject]?, but you can cast it to your object type with something like

if let myObjects = fetchedResultsController.fetchedObjects as? [MyObjectType] {
    for object in myObjects {
        // do some comparison to see if the object is in your downloaded data
    }
}

Another way to get the objects is to create a NSFetchRequest and use executeFetchRequest on your managed object context.

Upvotes: 0

Related Questions