簡體   English   中英

檢查名稱屬性是否已存在於 CoreData 中

[英]Check if name attribute already exists in CoreData

我有一個名為BankInfo的實體,它的一個參數是name ,它是一個字符串。 我只是想知道,有沒有一個辦法CoreData檢查,看看是否name中已經存在BankInfo無需檢索每BankInfo通過他們的個人目標與周期和檢查? 實現這一目標的最有效方法是什么?

您可以使用帶有謂詞fetch 請求來查找與某些屬性匹配的對象。 如果您只對具有給定鍵的對象的存在感興趣,請使用countForFetchRequest而不是實際獲取對象,並將結果集限制為一個對象:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"BankInfo"];
[request setPredicate:[NSPredicate predicateWithFormat:@"name = %@", theName]];
[request setFetchLimit:1];
NSUInteger count = [context countForFetchRequest:request error:&error];
if (count == NSNotFound)
    // some error occurred
else if (count == 0)
    // no matching object
else
    // at least one matching object exists

對於其他像我一樣,最終在這里尋找Swift 3解決方案的人,這里是:

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "BankInfo")
let predicate = NSPredicate(format: "name == %@", theName)
request.predicate = predicate
request.fetchLimit = 1

do{
    let count = try managedContext.count(for: request)   
    if(count == 0){
    // no matching object
    }
    else{
    // at least one matching object exists
    }
  }
catch let error as NSError {
     print("Could not fetch \(error), \(error.userInfo)")
  }

對於Swift 5,使用下面的代碼,它類似於一個贊成的答案,唯一的區別是使用 context.count 而不是 managedContext.count

let request : NSFetchRequest<MachineTypeTolerance> = MachineTypeTolerance.fetchRequest()
let predicate = NSPredicate(format: "machineType = %@", type)
request.predicate = predicate
request.fetchLimit = 1
do{
    let count = try context.count(for: request)
    //instead of managedContext use context,
    // where let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    if(count == 0){
        print("no matches")
    }
    else{
        print("match found")
    }
} catch let error as NSError {
    print("Could not fetch \(error), \(error.userInfo)")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM