Swift - How to get last insert id in Core Data, st

2019-06-10 07:28发布

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.

Please advice. Thank you.

1条回答
倾城 Initia
2楼-- · 2019-06-10 08:25

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)
查看更多
登录 后发表回答