1

So I have two Core Data entities. Listing and Comment. A listing can have multiple comments so Ive created a One-to-Many relationship between them.

extension Listing {

    @NSManaged var listingTitle: String?
    @NSManaged var comments: NSSet?
}

extension Comment {

    @NSManaged var comment: String?
    @NSManaged var commentId: String?
    @NSManaged var rating: Int32
    @NSManaged var username: String?
    @NSManaged var listing: Listing?

}

However, I cant seem to figure out how to add a Comment to a Listing?

I get the data from JSON blobs and parse the values from it, so I'd have something like this:

let comment = NSEntityDescription.insertNewObjectForEntityForName("Comment", inManagedObjectContext: moc) as! Comment

comment.username = "User1"

But how do I then assign that comment to a pre-defined Listing?

Hope that made sense. Thank you!

ardevd
  • 3,329
  • 5
  • 30
  • 55
  • 1
    Possible duplicate of [Saving CoreData to-many relationships in Swift](http://stackoverflow.com/questions/25127090/saving-coredata-to-many-relationships-in-swift) – DerailedLogic Jan 27 '16 at 21:39

2 Answers2

2

Comment has a to-one relationship to Listing. Just set this relationship.

newComment.listing = listing
Mundi
  • 79,884
  • 17
  • 117
  • 140
  • 1
    Ah, why didnt I think of that. However, how would I then go about retrieving all Comments assosicated with a given listing? – ardevd Jan 28 '16 at 08:06
0

You can write:

@NSManaged var comments: Set<Comment>?

And then you can (provided that you have an instance to a Listing):

listing.comments.insert(comment)
FranMowinckel
  • 4,233
  • 1
  • 30
  • 26