如何在具有一对多关系的核心数据实体中追加记录

时间:2018-11-09 15:10:09

标签: swift core-data

我有两个实体Mobile和User,其中Mobile具有属性名称,而user也具有名称属性。一个用户可以有多个移动设备,但移动设备只能有一个用户。场景是,当我输入用户实体中已经存在的用户名称时,它应该更新该user.mobile设置,而不是复制新用户。 这些是我的保存和提取功能

    func save () {
    if context.hasChanges {
        do {
            try context.save()
            print("saved succesfully")
        } catch {
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

func fetch<T: NSManagedObject>( _ objectType: T.Type) -> [T] {
    let  entityName = String(describing: objectType)
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)

    do {
        let fetchedObjects = try context.fetch(fetchRequest) as? [T]
        return fetchedObjects ?? [T]()
    } catch {
        print(error)
        return [T]()
    }
}

这就是我要添加的方式

       users = persistenceManager.fetch(User.self)
    if users.count > 1 {
    for val in users {

        if val.name == "Umar" {
            val.addToDevice(device)
            device.user = val
            persistenceManager.save()
        }
        else if val.name != nil  {
                            user.name = "Umar"
                            user.addToDevice(device)
            device.user = user
            persistenceManager.save()
        }
    }

1 个答案:

答案 0 :(得分:0)

您的问题缺少一些细节。 BUT让我假设我正确理解了你。

    let userName = "some name from user input"
    let user = MOUser.getUser(context, name: userName, createIfMissing: true)
    // here you have user with name required and not duplicated if already exists
device.user = user

并将静态函数添加到您的用户类或数据库协调器中

    static func getUser(moc: NSMaagedObjectContext, name: String, createIfMissing: Bool) -> MOUser? {
        let request: NSFetchRequest<MOUser> = MOUser.fetchRequest()
        request.predicate = NSPredicate(format: "\(#keyPath(MOUser.name)) = %@", name)
        request.fetchLimit = 1
        var result: MOUser? = (try? moc.fetch(request))?.first

        if result == nil && createIfMissing {
            result = MOUser(context: moc)
            result?.name = name
        }
        return result
    }