简体   繁体   English

核心数据搜索和更新

[英]Core data search and update

I'm struggling to find a tutorial whereby I can update a core data entity.我正在努力寻找可以更新核心数据实体的教程。 For example, if I have a field and an add button, I know how to add it to an entity.例如,如果我有一个字段和一个添加按钮,我知道如何将其添加到实体中。 This field can add names: john, jack, jill but if I add john again I want to ensure that the duplicate is not entered.此字段可以添加名称:john、jack、jill 但如果我再次添加 john,我想确保不输入重复项。

Here is my add code.这是我的添加代码。

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

let entity = NSEntityDescription.entity(forEntityName: "UserAccountTbl", in: context)!
let person = NSManagedObject(entity: entity, insertInto: context)

person.setValue(NameSurname, forKeyPath: "nameSurname")

try context.save()

Swift 4斯威夫特 4

func isEntityAttributeExist(id: Int, entityName: String) -> Bool {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let managedContext = appDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        fetchRequest.predicate = NSPredicate(format: "id == %@", id)

        let res = try! managedContext.fetch(fetchRequest)
        return res.count > 0 ? true : false
      }

Objective C目标 C

NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"UserAccountTbl"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"nameSurname == %@", ameSurname];
[fetch setPredicate:predicate];
YourObject *obj = [ctx executeRequest:fetch];

if(!obj) {
    //not there so create it and save
    obj = [ctx insertNewManagedObjectForEntity:@"UserAccountTbl"]; //typed inline, dont know actual method
    obj. nameSurname = NameSurname;
    [ctx save];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM