Ser Pounce
Ser Pounce

Reputation: 14571

Check if name attribute already exists in CoreData

I have an entity called BankInfo, and one of its parameters is name which is a string. I'm just wondering, is there a way in CoreData to check and see if a name already exists in BankInfo without having to retrieve every BankInfo object and cycle through them individually and check? What would be the most efficient way to accomplish this?

Upvotes: 7

Views: 9859

Answers (3)

Muskan Arora
Muskan Arora

Reputation: 21

For Swift 5 use the below code, it similar to one of the upvoted answers, the only difference being use context.count instead of 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)")
}

Upvotes: 2

Arpit Dongre
Arpit Dongre

Reputation: 1713

For other, who like me, ended up here looking for Swift 3 solution, here it is:

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)")
  }

Upvotes: 12

Martin R
Martin R

Reputation: 540145

You can use a fetch request with a predicate to find objects matching certain attributes. If you are only interested in the existence of an object with the given key, use countForFetchRequest instead of actually fetching the objects, and limit the result set to one object:

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

Upvotes: 22

Related Questions