Check if name attribute already exists in CoreData
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
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)")
}