Recently, I've been working working on small database using Core Data. The project is developing in Swift 3. After creating all relationships between attributes and entities I started thinking about using data from Core Data to get some results. First I wanted simple summing but later I decided that I also want to group some added values.
To be clear - I don't want to group attributes inside entity, but group values inside attribute. Let's say that we have attribute called 'Colors' with values as:
Colors have a relationship with other entities so user can add many values with red color or green color. For example:
apples - green
peaches - green
strawberries - red
raspberries - red
How to group Colors and show only those values that has been added? Well, we will need NSFetchRequest.
Let's start with the easy one. First, we need to create function that will give us NSFetchRequest with grouped values of Colors. Our code will look like this:
This part lets us to sort Fruits - by date, but of course we can use another value. We can also add more sort descriptors. Then, we move to Colors:
As you can see, first we have Fruits sorted by date, then we can set filters, which are in that case Colors. Finally, we should get only those Colors that have added values (ie Fruits). Results can be print or simply (that was my case) put into tableView.
Stay tuned, as next time I'll show you more simple tricks that can be done with Core Data on Swift. Follow us on Twitter to make sure you won't miss my next blogpost.
Meanwhile why won't you take a look at games we created for the Ludum Dare 27 hackathon. Have fun!
photo by: Álvaro Serrano, unsplash.com