我的应用程序有许多单词列表,每个都包含许多单词。在一个视图控制器中,tableView列出单词列表,然后子视图控制器有一个包含单词的tableView。segue传递wordList实体。但我不知道如何在传递的单词列表上执行提取请求,然后获取所有单词。错误信息如下所示。我需要执行一个提取请求,而不是查看属性,以便进行排序。
提前谢谢你的帮助。。。。
WordList实体有一个属性listName,并且关系:words,destination:Word,Inverse:WordList
Word实体有一个属性wordName,wordIndex和relationships:wordList,destination:wordList,Inverse:words
我的WordsViewController看起来像:

class WordsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate  {

var coreDataStack: CoreDataStack = (UIApplication.sharedApplication().delegate as! AppDelegate).coreDataStack

var wordList: WordList?
var words = [Word]()
var word: Word?

override func viewDidLoad() {
    super.viewDidLoad()

    // set the title of the scene
    title = wordList?.listName

   // fetch all the words that are part of the wordList passed to this VC.
   let fetchRequest = NSFetchRequest(entityName: "Word")
    let wordListPredicate = NSPredicate(format: "word.wordList == '\(wordList)'") // GIVES AN ERROR SAYING UNABLE TO PARSE THE FORMAT STRING "word.wordList == 'Optional(<WordList:0x...

    let sortDescriptor = NSSortDescriptor(key: "wordIndex", ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]

    fetchRequest.predicate = wordListPredicate

    do {
        if let results = try coreDataStack.managedObjectContext.executeFetchRequest(fetchRequest) as? [Word] {
            words = results
        }
    } catch {
        fatalError("There was an error fetching system person")
    }
}

最佳答案

不能使用字符串插值来生成谓词,请使用
取而代之的是参数替换。在您的情况下(因为var wordList: WordList?
可选):

if let theWordlist = wordlist {
    let wordListPredicate = NSPredicate(format: "wordList == %@", theWordlist)
} else {
    // wordlist is nil ...
}

还要注意,谓词中的"word.wordList == "应该是
"wordList == ",因为“wordList”是“Word”的属性
实体。
有关详细信息,请参见Predicate Format String Syntax
在“谓词编程指南”中。

关于swift - 有关关系属性的核心数据获取请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34253182/

10-09 06:31