Search code examples
iosswiftcore-dataxcode6

Swift - How to get last insert id in Core Data, store it in NSUserDefault and predicate


I already create a new entity and save it. Then I want to grab last insert id from first entity then save it into second entity as a reference id.

let appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)

        let userContext: NSManagedObjectContext = appDel.managedObjectContext!
        let userEn = NSEntityDescription.entityForName("UserEntity", inManagedObjectContext: userContext)

        var newUser =  Users(entity: userEn!, insertIntoManagedObjectContext: userContext)

        newUser.uname = "Nurdin"

        userContext.save(nil)

Then how to save last insert id into NSUserDefault? Because I want to predicate with existing data inside CoreData for matching purpose.


Solution

  • you magically ask core data for the latest id...

    but for your example. just add a line after the save to store the ID...

        let string = user.objectID.URIRepresentation().absoluteString
        NSUserDefaults.standardUserDefaults().setObject(string, forKey: "userID")
    

    ... vice-versa ...

        let oidString = NSUserDefaults.standardUserDefaults().stringForKey("userID")
        let url = NSURL(string: oidString)
        let objectID = persistentStoreCoordinator.managedObjectIDForURIRepresentation(url)