如何从实体中获取具有相同对象的对象列表? - ios

时间:2014-11-30 10:27:07

标签: ios core-data swift

我的CoreData中有这个数据库结构。我需要获得具有相同Task对象的Task实体中的所有Group个对象的列表(即,组包含我想要获得的这些任务)。我如何用Predicates或其他东西做到这一点? enter image description here

我试过这段代码:

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!
}

1 个答案:

答案 0 :(得分:1)

首先,获取您需要过滤的组(我认为您的代码中为“group”)。确保它是一个有效的对象,否则在用!打开后会出现崩溃。将谓词添加到提取的结果控制器中,如下所示:

fetchRequest.predicate = NSPredicate(format:"group = %@", group)

这就是全部; - )。