我可以将多个谓词应用于NSFetchRequest吗?手动解析我的结果会更好吗?

Liz*_*zza 32 iphone core-data nspredicate nsfetchrequest

好的我有一个基本的iPad应用程序,要求用户提供5个搜索/过滤条件.根据这些数据,我需要转到我的核心数据db,并提取符合该条件的任何托管对象.看起来我需要在同一个请求中应用多个谓词,这可能吗?或者我可以写一个非常长的花哨的谓词?有多个要求?我应该怎么做?

通过获取请求获取所有实体是不是一个好主意,然后循环遍历每个数组并抓住我找到的符合我搜索条件的任何对象?

请指教!

Rog*_*Rog 84

是的,这是可能的.您正在寻找复合谓词,这里是AND谓词的示例:

NSPredicate *compoundPredicate 
   = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray of Predicates]];
Run Code Online (Sandbox Code Playgroud)

您也可以使用notPredicateWithSubpredicates,并orPredicateWithSubpredicates根据您的需要.

链接到文档https://developer.apple.com/documentation/foundation/nscompoundpredicate

  • Thanx man,我尝试通过编写NSString并将其作为格式传递给谓词来实现.这很好用,但不是日期!我浪费了一天的工作.这是创建过滤器的方法:D (3认同)

den*_*den 5

斯威夫特 4

let fetchRequest: NSFetchRequest<YourModelEntityName> = YourModelEntityName.fetchRequest()

let fooValue = "foo"
let barValue = "bar"

let firstAttributePredicate = NSPredicate(format: "firstAttribute = %@", fooValue as CVarArg)
let secondAttributePredicate = NSPredicate(format: "secondAttribute = %@", barValue as CVarArg)

fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [firstAttributePredicate, secondAttributePredicate])
Run Code Online (Sandbox Code Playgroud)

NSCompoundPredicate可以在此处找到有关不同类型构造函数的更多信息