Swift - 如何在Core Data中获取最后一个插入ID,将其存储在NSUserDefault和谓词中 [英] Swift - How to get last insert id in Core Data, store it in NSUserDefault and predicate

查看:186
本文介绍了Swift - 如何在Core Data中获取最后一个插入ID,将其存储在NSUserDefault和谓词中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个新实体并保存。然后我想抓住最后从第一个实体插入id,然后将其保存为第二个实体作为引用id。

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)

如何保存最后插入id到NSUserDefault?因为我想使用CoreData中的现有数据进行谓词匹配。

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

请咨询。谢谢。

推荐答案

您不可思议地要求核心数据获取最新的ID ...

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

但是对于你的例子。只是在保存后添加一行来存储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)

这篇关于Swift - 如何在Core Data中获取最后一个插入ID,将其存储在NSUserDefault和谓词中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆