ardevd
ardevd

Reputation: 3407

Saving data into a One-to-many CoreData relationship in Swift

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!

Upvotes: 1

Views: 572

Answers (2)

FranMowinckel
FranMowinckel

Reputation: 4343

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)

Upvotes: 0

Mundi
Mundi

Reputation: 80265

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

newComment.listing = listing

Upvotes: 2

Related Questions