0
votes

I have a data model with several entities. For entities joined in one-to-one relationships, after a fetch from one entity, I am able to access an attribute from the other entity through the relationship.

//class for artists

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@class Songs;

@interface Artists : NSManagedObject
@property (nonatomic, retain) NSString * artistname;
//this is relationship
@property (nonatomic, retain) Songs *songs;

//class for Songs
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@class Artists;

@interface Songs : NSManagedObject
@property (nonatomic, retain) NSString * songname;
//this is relationship
@property (nonatomic, retain) Artists *artists;

If the relationship is One-to-one, once I have performed a fetch of artists and have a managedobjectcontext, I can get the song of each artist using the following:

NSLog(@"song for one hit wonder%@",self.artists.songs.songname);

When I change the relationship from one-to-one to one-to-many, i.e. one artist, many songs, this no longer works and throws an error that references [_NSFaultingMutableSet songname

I have tried to access the song using value for key without success.

NSLog(@"songs:%@",self.artists.songs.valueForKey[@"songname"]);

Also, I've tried to incorporate NSSet somewhere since the error message references mutable set and one-to-many relationships are supposedly captured that way but I cannot figure out how to use NSSet.

NSSet *songs = self.artists.songs.songname;//gives incompatible pointer type warning

Any suggestions one how to retrieve values from another entity in the case of a one-to-many relationship would be greatly appreciated.

1

1 Answers

1
votes

First of all, it's a bit confusing to set the name of a Core Data entity to a plural form because it suggests always many.

If you change the relationship in the model from one-to-one to one-to-many you have to change the type in the NSManagedObject subclass to NSSet for example

@property (nonatomic, retain) NSSet *songs;

You can prove it by recreating the NSManagedObject subclasses automatically in Xcode.