我的CoreData
中有这个数据库结构。我需要获得具有相同Task
对象的Task
实体中的所有Group
个对象的列表(即,组包含我想要获得的这些任务)。我如何用Predicates
或其他东西做到这一点?
我试过这段代码:
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Task", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "createdate", ascending: false)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = [sortDescriptor]
var predicate = NSPredicate(format: "group.createdate == %@", group!.createdate)
fetchRequest.predicate = predicate
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Details")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
var error: NSError? = nil
if !_fetchedResultsController!.performFetch(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
答案 0 :(得分:1)
首先,获取您需要过滤的组(我认为您的代码中为“group
”)。确保它是一个有效的对象,否则在用!
打开后会出现崩溃。将谓词添加到提取的结果控制器中,如下所示:
fetchRequest.predicate = NSPredicate(format:"group = %@", group)
这就是全部; - )。