【问题标题】:Implementing predicates but resulting in 1 fetchedObject实现谓词但产生 1 个 fetchedObject
【发布时间】:2017-02-06 12:56:23
【问题描述】:

在实现 Predicate 后,我在从 CoreData 获取结果时遇到了一些困难。该实现只产生 1 个 fetchedObject,我不知道为什么。

class PhotoAlbumViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, MKMapViewDelegate {

var pin: Pin!

lazy var context: NSManagedObjectContext = {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.stack!.context
    }()

lazy var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
        let fetchedRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Photo")
        fetchedRequest.sortDescriptors = []
        fetchedRequest.predicate = NSPredicate(format: "pins == %@", argumentArray: [self.pin])
        return NSFetchedResultsController(fetchRequest: fetchedRequest, managedObjectContext: self.context, sectionNameKeyPath: nil, cacheName: nil)
    }()

override func viewWillAppear(_ animated: Bool) {

    super.viewWillAppear(animated)

    do {
        try fetchedResultsController.performFetch()

    } catch let error as NSError {
        print("Unable to perform fetch: \(error.localizedDescription)")
    }

    let fetchedObjects = fetchedResultsController.fetchedObjects
    print(fetchedObjects.count) //returns 1 only

}

Photo 实体和 Pin 之间都有关系。

非常感谢这里的任何建议,谢谢!

【问题讨论】:

  • 您需要 Apple 推荐的 sortDescriptors。
  • 我怀疑只有一个对象与谓词匹配。
  • 为什么需要谓词?
  • 谓词对搜索有用!如果要获取所有数据?删除它,改用 sortDescriptors
  • “pins”是一对多的关系吗?那么你可能想要NSPredicate(format: "ANY pins == %@", self.pin)

标签: ios swift core-data nspredicate


【解决方案1】:

Pins to Photos 被认为是一对多的关系。我在设置模型时错过了这部分,将其设置为一对一的关系。用新的模型版本修改它后,它可以正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 2017-05-03
    • 2016-06-23
    • 2013-09-24
    • 1970-01-01
    相关资源
    最近更新 更多