I successfully configured the implementation of RestKit binding to CoreData in a new Swift-based application (currently Xcode 6 beta 3). I know that import mappings work from my RestKit JSON call, because I can check the sqlite database and see my data. However, I cannot get data from the data store in NSFetchRequest. What am I doing wrong?
I will take care of setting up and removing RestKit because it is pretty standard and seems to work just fine. So here is my AppDelegate request code, which does not seem to work:
var currentUser: User? { if !_currentUser { var error: NSError? = nil let request = NSFetchRequest(entityName: "User") let recordCount = self.managedObjectContext.countForFetchRequest(request, error:&error) NSLog("user records found: \(recordCount)") var result = self.managedObjectContext.executeFetchRequest(request, error:&error) for resultItem : AnyObject in result { _currentUser = resultItem as? User if _currentUser { NSLog("Fetched User for \(_currentUser!.firstname) \(_currentUser!.lastname)") } } } return _currentUser; }
self.managedObjectContext references this from my AppDelegate to get the context from the shareObject RestKit:
var managedObjectContext: NSManagedObjectContext { return RKObjectManager.sharedManager().managedObjectStore.mainQueueManagedObjectContext }
The fetch request seems to be successful since a breakpoint in the for / in loop arises. However, when I check resultItem or _currentUser objects, they appear empty, and the NSX "if _currentUser" never fires.
Any ideas? Am I making the wrong assumptions about returning data to Swift?
EDIT 2:
The problem is related to my attempt to cast the resultItem object to Optional. If you declare _currentUser without an option and delete how? an optional query listing returns the correct user object:
for resultItem : AnyObject in result { _currentUser = resultItem as User NSLog("Fetched User for \(_currentUser.firstname) \(_currentUser.lastname)") }
EDIT: I added a record counter before the main query to fetch, and it correctly shows 1 record. So there is something wrong with the way I am trying to map the selection result to my custom object. Here is my user class:
import Foundation import CoreData class User: NSManagedObject { @NSManaged var id: Int32 @NSManaged var createdAt: NSDate @NSManaged var udpatedAt: NSDate @NSManaged var username: String @NSManaged var email: String @NSManaged var firstname: String @NSManaged var lastname: String @NSManaged var organization: String @NSManaged var tokens: NSArray }