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

隐身守侯 提交于 2019-12-08 12:04:04

问题


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:


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)


来源:https://stackoverflow.com/questions/28363335/swift-how-to-get-last-insert-id-in-core-data-store-it-in-nsuserdefault-and-pr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!