检查CoreData中是否已存在名称属性 [英] Check if name attribute already exists in CoreData
问题描述
我有一个名为 BankInfo
的实体,其参数之一是 name
,这是一个字符串。我只是想知道,在 CoreData
中有一种方法来检查名称
是否已存在于 BankInfo
,而不必检索每个 BankInfo
对象,并逐个循环检查?什么是最有效的方法来完成这个?
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?
推荐答案
您可以使用谓词对象匹配某些属性。
如果您只对给定键的对象的存在
感兴趣,请使用 countForFetchRequest
,而不是实际提取对象,并将结果集限制为一个对象:
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
这篇关于检查CoreData中是否已存在名称属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!