Swift fetch request returns 0 results, even though there are clearly 192 results

时间:2016-04-04 16:50:19

标签: ios swift core-data interpolation nsmanagedobjectcontext

I make my fetch request like so :

let pageFetchRequest = NSFetchRequest(entityName: "Page")
let results = try managedObjectContext.executeFetchRequest(pageFetchRequest)

Here, results will return 0 results {}.

But I do this by itself :

managedObjectContext.executeFetchRequest(pageFetchRequest)

I get all 192 results. So long as I don't assign it to a variable such as results. Why is that? Does assigning it or using the method try prevent this from working?

Update

This is the full post. Notice how I'm using managedObjectContext twice for two different related requests. Maybe that's what is botching my results up?

    let managedObjectContext = self.managedObjectContext

    for item in items {
        let word = Word(chapter: Int(item.chapter)!, verse: Int(item.verse)!, sanskrit: item.sanskrit, english: item.english, insertIntoManagedObjectContext: managedObjectContext)

        // Assign the Page
        let pageFetchRequest = NSFetchRequest(entityName: "Word")
        let chapterPred = NSPredicate(format: "(chapter = %d)", Int(item.chapter)!)
        let versePred   = NSPredicate(format: "(verse = %d)", Int(item.verse)!)
        pageFetchRequest.fetchLimit = 1
        pageFetchRequest.predicate = NSCompoundPredicate(type: .OrPredicateType, subpredicates: [chapterPred, versePred])

        do {
            let results = try managedObjectContext.executeFetchRequest(pageFetchRequest)
            if let page = results.first as? NSManagedObject {
                word.setValue(page, forKey: "page")
            }

        } catch let error as NSError {
            print("Could not save \(error), \(error.userInfo)")
        }

        do {
            try managedObjectContext.save()
        } catch let error as NSError {
            print("Could not save \(error), \(error.userInfo)")
        }

1 个答案:

答案 0 :(得分:0)

So evidently the answer.. I think.. was to create a separate managedObjectContext that wouldn't be confused with the parent one.. Like so :

                let appDelegate          = UIApplication.sharedApplication().delegate as! AppDelegate
                let secondManagedContext = appDelegate.managedObjectContext
                let pageFetchRequest = NSFetchRequest(entityName: "Page")Int(item.verse)!)
                pageFetchRequest.fetchLimit = 1
                pageFetchRequest.predicate = NSCompoundPredicate(type: .OrPredicateType, subpredicates: [chapterPred, versePred])

And then I had to also write this :

                do {
                    var results:[NSManagedObject]
                    results = try secondManagedContext.executeFetchRequest(pageFetchRequest) as! [Page]
                    if let page = results.first {
                        word.setValue(page, forKey: "page")
                    }