Reputation: 154
I saw already some approaches but nothing which would solve my problem.
I create two entities, Shop and Article. Shop has the relationship "articles" and Article "shop", both are many to many and ordered relationships.
For the shop I have one CollectionViewController and for Articles TableViewController. After selecting one Shop I send it via segue to the ArticleTableViewController, where I can add Articles to the current shop.
ArticleTableViewController
var articles: [Article] = []
var currentShop: Shop?
@IBAction func pressAddButton(_ sender: UIButton) {
let article = Article(context: managedContext!)
article.name = "Milk"
currentShop?.addToArticles(article)
saveManagedContext()
tableView.reloadData()
}
func loadArticles () {
let articleFetchRequest: NSFetchRequest<Article> = Article.fetchRequest()
articleFetchRequest.predicate = NSPredicate(format: "shop = %@", currentShop!)
do {
articles = try managedContext.fetch(articleFetchRequest)
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
func saveManagedContext() {
do {
try managedContext?.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
If I build and run and select one shop, the app terminated with the reason: 'NSInvalidArgumentException', reason: 'to-many key not allowed here'
I think the problem is the predicate, because if I comment it out and run again and then select the shop it works fine, but all shops have the same articles that I added.
How to fetch just the articles for the selected Shop?
Upvotes: 2
Views: 1548
Reputation: 6635
Try
NSPredicate(format: "ANY shop = %@", currentShop!)
Or, alternatively, can you just use currentShop.articles
? That will return a Set
, which may not suit your purpose in this case, but... generally you can just follow relationships.
Upvotes: 6