Alex
Alex

Reputation: 5278

RestKit + CoreData, understanding RKManagedObjectRequestOperation

I am using RestKit to map an API to CoreData entities. My question is about the timing of how the mapping/save works, as my code is not working as expected.

Currently, the request successfully completes, but then when I call self.getUsers() it still shows 0 objects in my CoreData DataModel.

However, when I re-run the app, and print self.getUsers() at the top of the file, I see my user! Therefore the save is happening, just after my self.getUsers() line runs...

I am misunderstanding the timing of when the User NSManagedObject is actually being saved, since I assume my call of self.getUsers() is happening too early in the chain.

Here is my code to help you understand:

var request: NSURLRequest = NSURLRequest(URL: NSURL(string: "MY_API_URL_HERE")!)

var operation: RKManagedObjectRequestOperation = RKManagedObjectRequestOperation(request: request, responseDescriptors: [responseDescriptor])
operation.managedObjectContext = managedObjectStore.mainQueueManagedObjectContext
operation.managedObjectCache = managedObjectStore.managedObjectCache
operation.setCompletionBlockWithSuccess({ (operation: RKObjectRequestOperation!, result: RKMappingResult!) -> Void in
    println("Success with result: \(result)")

    var user: User = (result.array() as NSArray).firstObject as User

    // Calls a func that makes an NSFetchRequest on the 'User' Entity 
    self.getUsers()


}, failure: { (operation: RKObjectRequestOperation!, error: NSError!) -> Void in
    println("Failed with error: \(error.localizedDescription)")
})

And then the getUsers func:

func getUsers() {

    var fetchRequest = NSFetchRequest(entityName: "User")

    if let fetchResults = self.appDelegate.context.executeFetchRequest(fetchRequest, error: nil) as? [User] {
        println(fetchResults.count)
        if (fetchResults.count > 0) {
            for managedObject:User in fetchResults {
                println("Found user")
                println(managedObject.valueForKey("id"))
            }
        }
    }
}

Upvotes: 3

Views: 207

Answers (1)

Wain
Wain

Reputation: 119031

Restkit maintains its own managed object context (hierarchy), so you need to ensure you're using the appropriate context. The managed object store (you usually only have one, possibly used by multiple object managers) provides a mainQueueManagedObjectContext, so access it using:

[[RKManagedObjectStore defaultStore] mainQueueManagedObjectContext]

Upvotes: 1

Related Questions