CoreData sort on to-many relationship - iphone

I'm writing an iOS app which has store of person records, and needs to display lists them sorted in particular ways. There are a variable number of these orderings, and they are generated on the fly, but I would like them to be stored in the datastore. The SQL way to do this is to have a ListPositions table with a list name, an id into the persons table, and a sort key. Then, to display a particular list, I can select all list ListPositions with a given name, pull in the referenced persons, and sort on the sort key. Trying to do this in CoreDatat, however I run into problems. I am trying to do this using a schema like:
Person:
Name
DOB
etc...
positions -->> ListPosition
ListPosition:
listName
sortKey
person --> Person
Then, I can get all the Persons in a given list with the NSPredicate
[NSPredicate predicateWithFormat:#"ANY positions.listName like %#", someList];
This allows me to dynamically add lists against a large set of Persons. The problem is that I am unable to use the sortKey field of ListPosition to sort the Persons. What NSSortDescriptor will do this? And if it is not possible to sort a fetch on the property of one element of a to-many relationship, what is another way to get multiple, dynamic orderings in coredata? I am displaying the lists with a NSFetchedResultsController, so I can't put the lists together myself in memory. I need to do it with a single NSFetchRequest.

You're right-- following a to-many relationship returns an NSSet, which has no inherent sorting. To get sorted results there are a couple of options:
Assuming that Person/ListPosition is a two-way relationship, do a new fetch request for ListPosition entities. Make the predicate match on the "person" relationship from ListPosition, which would look something like [NSPredicate predicateWithFormat:#"person=%#", myPerson]. Use whatever sort descriptor you need on the fetch request.
Follow the relationship as you're doing, which gives you an NSSet. Then use NSSet's -sortedArrayUsingDescriptors: method to convert that to a sorted array.

I think the best approach in this case would be to fetch on ListPosition entity instead. Add the sort Descriptor for sortKey (it would work in this case because the fetch request is on ListPosition entity) and prefetch the Person associated with the the list name using setRelationshipKeyPathsForPrefetching for "person" on the fetch request.
[NSPredicate predicateWithFormat:#"listName like %#", someList];

If I understand your model correctly, each Person has one ListPosition for each list in which it participates. Let's say we have acsending list by their names, so X people have X list positions with the same listName and sortKey.
I would create entity List, that would contain the sortKey attribute and then use it in sort descriptor.
entity List:
- sortKey : string
- ascending : bool
Create sort descriptor and use it in fetch request:
[NSSortDescriptor sortDescriptorWithKey:chosenList.sortKey ascending:chosenList.ascending];
Then you may have as many Lists as you want and you can easily use its sort key to sort all people.
If you want to store the positions in database (you didn't mention attribute index in your ListPosition, or anything similar), you can create “joint entity”:
entity PersonInList:
- index : integer
- person -> Person
- list –> List
Another idea is having ordered set of Person objects directly in List entity.

Get the ListPosition (it will come as a NSMutableSet). Then do a sort on the Set, like this:
NSMutableSet *positionsSet = [personEntity mutableSetValueForKey:#"positions"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"yourSortKey" ascending:NO];
NSArray *positionsSortedSet = [positionsSet sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
That will give you a sorted out array according to your key.

I usually add an index field (type NSNumber) to an entity. It's very easy to calculate index in adding item. just by
object.index = person.positions.count
so, actually you don't need positions field but positions relationship. connect person entity to ListPosition entity would be enough.

Related

Core data cross referencing two relationships

I have a data structure in Core Data like so...
User
Item
Category
User has a toMany relationship "FavouriteItems" to the Item entity.
Category also has a toMany relationship "Items" to the Item entity.
The user can select favourite items from any categories they wish. At the moment I am listing all the items and then displaying the Category alongside.
What I'd like to do is display all the user's favouriteItems for a selected Category.
i.e. select all the Items that have a relationship with Category x and User y.
I'm currently doing this by getting all the Items through one relationship (i.e. User.favouriteItems) and then filtering the NSSet using a block predicate.
Is it possible though to do this with a simple CoreData predicate?
Hmm... thinking about it would a predicate like this work...
[NSPredicate predicateWithFormat:#"interestedUser.id = %# AND category.id = %#", user.id, category.id];
And then run a fetch request on the item entity?
Would that work?
Shooting pretty blind as that's an awkward scenario to set up just to answer a question but perhaps
If you are filtering an array of Items which has the correct inverse relationships set up.
[NSPredicate predicateWithFormat:#"%# IN interestedUsers AND %# IN categories",
someUser,
someCategory];
Basically the Item has many users (interestedUsers) so we are saying is our user in this collection.
Similarly the Item has many categories (categories) so we are saying AND is our chosen category in this collection.

How to use predicate to get ordered list of Core Data NSSet relationship?

I have an instance of the Department entity, which in turn has a relationship to the Employee entity via the 'employees' to-many relationship.
How would I construct my NSPredicate to return an array of employees within the specific department, in employeeNumber order, from this Department instance?
A predicate's purpose is to filter items, not to sort them. Use your fetch request's sortDescriptors property to determine how the results are sorted.
Alternatively, if you're accessing the relationship via the object's properties, use the NSSet method sortedArrayUsingDescriptors: to create a sorted array from the set of objects.

how to obtain an ordered list of coredata managed objects via accessing them via a relationship?

How to obtain an ordered list of coredata managed objects via accessing them via a relationship?
That is:
have the following entities: LIST, LIST_ITEM (includes an 'Order' field), and ITEM.
assume that I have already fetched the list I want to work with
I can then use the coredata relationships to get the LIST_ITEMS via using the relationship: e.g. "list1.listItems", and then for each of these LIST_ITEMS I can get the ITEM ("listItem1.item")
But if I really just want, from the LIST, an ordered list of ITEMS from the list, based on the "Order" field in the LIST_ITEM, what is the easiest way of doing this?
You can sort the items returned by the relationship using an NSSortDescriptor just as you would in a regular fetch request. For example:
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"order" ascending:YES] autorelease];
NSArray *sortedListItems = [list1.listItems sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
The key method here is [NSSet sortedArrayUsingDescriptors:]
I think that I understand the question correctly, but I think the best way to get lists from CoreData is create a compoun predicate and then search for items that way. For example if I am looking for only Events (entity) on a certain day, for a specific User (another entity). Then I can create an NSFetchRequest for the Event entry and specify and NSPredicate in the form of (user.name==%#) AND (event.date==%#) specifying the user's name and date

Sort entity by subquery - NSSortdescriptor

I have 3 core data entities:
Entity A and Entity B and User which are related like
Entity A < ------ >> Entity B <<----- > User
I want to sort the entries in Entity A by the number of entries in entity B for that specific user.
I could do this:
fetch all Entity A entries
For each entry - fetch the number of Entity B entries for that entry and for the current user
Count the number of entries for that Entity A entry store and then sort.
This though seems awfully stupid.
Is there anyway i could sort Entity A with a NSSortDescriptor perhaps by using a Subquery?
Or if you know any other way i should solve this?
You can't sort on a collection operator so there is no way to us a sort descriptor to do what you want. Subqueries, like all predicates, simply find objects based on test, they don't sort them.
The easiest solution would be to add a transient attribute, say bCount, to EntityA. Then have the getter method return a count of related EntityB objects:
-(NSNumber *) bCount{
return [NSNumber numberWithInt:[self.bs count]];
}
Then sort your EntityA objects on the bCount key.

Core data many-to-many relationship - Predicate question

In my Core Data model I have two entities: List and Patient. List has an attribute called 'name'.
A List can have any number of Patients and each Patient can belong to any number of different lists. I have therefore set a relationship on List called 'patients' that has an inverse to-many relationship to Patient AND a relationship on Patient called 'lists' that has a to-many relationship to List.
What I'm struggling to figure out is how to create a Predicate that will select all Patients that belong to a particular List name.
How would I go about this? I have never used relationships before in Core Data.
This seems to work OK:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(ANY lists == %#)", myList];
Where myList is an actual List entity.
Given a data model like:
List <<——>> Patient,
you can find all Patient instances that belong to a list with a particular name with a fetch request on the Patient entity using a predicate like:
[NSPredicate predicateWithFormat:#"ANY lists.name LIKE[cd] %#", listName]
assuming listName is an NSString instance with the list name you want. LIKE[cd] does a case-insensitive and diacritic-insensitive comparison.
It sounds like your data model is this:
List <<-->> Patient
I would think that if you know the particular list name, then you know the particular list object. If so, you can just grab the patients using the to-many relationship from List to Patient--it is a set of patient objects. For example, if the relationship from List to Patient is named "patients":
NSSet *patientSet = listObject.patients;
Note: this requires that you create subclasses for your managed objects so you can access the attributes and relationships as properties on your objects.
If you only know the list name for some reason, and you are fetching Patient objects, then you can create a predicate using the to-many relationship from Patient to List (assume it's named "lists" and the list's name in a string named "listName"):
NSPredicate *pred = [NSPredicate predicateWithFormat:#"ANY lists.name == %#",listName];
Ten years later, some more info !
Just some more info on the fantastic #GarryPettet answer,
Say you have entity CD_Person and aPerson is one of those. IE:
var aPerson: CDPerson
Say you have an entity CD_Pet
CD_Person has a relationship .pets which is a one-to-many CD_Pet
So just to be clear,
aPerson.pets
is indeed a Set of CD_Pet entities.
Almost certainly you'll have an id field which comes from your data source.
(Aside, .id must be an Int64 in your core data entity, even if it's a smaller int in your source data)
Two ways to go!
BOTH this
let p = NSPredicate(format: "(ANY pets == %#)", aPerson )
AND this
let p = NSPredicate(format: "(ANY pets.id == %lld)", aPerson.id)
... work perfectly, both are possibilities.
So there's two ways to go!
(PS: Don't forget the lld .. # won't work for Int64!)
Both work fine in the common situation where you have a "many-to-many" relationship.