0
votes

I have two entities in a Core Data Model like these: A <<--->> B.
Entity B has an attribute name which is a string object and a relationship AObjects to A; instead, entity A has got a relationship BObjects to B.
Now I want to get a list of all BObjects connected with A entity and then, I want to show their names in a label.

Is this possible? I know CoreData doesn't support many-to-many relationships...
Thanks!

2

2 Answers

2
votes

I think you may not have fully described your situation, because of course Core Data absolutely does support many-to-many relationships. I suspect you may mean that an NSFetchedResultsController does not support many-to-many relationships? As far as I've been able to determine, that is correct. (Edit: It is possible to use an NSFetchedResultsController with many-to-many relationships... it is just not very obvious how to do it.)

To do this without an NSFetchedResultsController, identify/fetch the A entity you are interested in, and then traverse the relationship you are interested in. So, if you already know that you are interested in a specific A object that I will call theAObject, with the class names A and B, you can just traverse the relationship using dot syntax and fast enumeration using something like the following:

for (B *theBObject in theAObject.BObjects) {
    NSLog(@"theBObject.name: %@.", theBObject.name);
    // Run whatever code you want to here on theBObject.
    // This code will run once for each B Object associated with theAObject 
    // through the BObjects relationship.
}

Alternatively, you can set up a fetch request to get a set of AObjects you are interested in, and then traverse BOjects relationship for each of them. It does not make any difference that it is a many-to-many relationship... each AObjecct will return all B objects that are in its BObjects relationship.

Later Now, you say you want to get all the names, and display it in a label. Let's break that down for you:

NSString *myLabel = null;
// You may of course want to be declaring myLabel as a property and @synthesising
// it, but for the sake of a complete example we'll declare it here which means 
// it will only have local scope.

for (B *theBObject in theAObject.BObjects) {
    myLabel = [myLabel stringByAppendingString:theBObject.name];    
    // Add a line break in the string after each B object name.
    myLabel = [myLabel stringByAppendingString:@"\n"];
}

// Do something with your myLabel string to set your desired label.
0
votes

You could try a predicate like this:

NSPredicate* fetchPredicate = [NSPredicate predicateWithFormat: @"any AObjects = %@", [NSManagedObjectID of an A]];