ardevd
ardevd

Reputation: 3407

How to assign one-to-many relationship objects to variable?

Apologies for the confusing and probably inaccurate title.

At any rate, I have two CoreData entities. Listing and Comment. A listing can have multiple comments so the entity models reflect this.

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?

}

At some point in the app I want to populate a UITableView with the comments but I'm having a bit of a hard time doing so.

var listing: Listing?

override func viewDidLoad() {
    super.viewDidLoad()

    //I assumed I could do this
    var comments: [Comment] = [Comment]()
    comments = listings?.comments // This throws an error saying NSSET cant be assigned to type [Comment]

Could anyone guide me to the correct way of accomplishing what I'm trying to do here? I can see the issue being related to the fact that in the Listing entity the commments are defined as a NSSet of an udefined type, so I probably cant assign that NSSet directly to an array of Comment.

Thank you!

Upvotes: 0

Views: 237

Answers (2)

Kiran Jasvanee
Kiran Jasvanee

Reputation: 6554

You can access your above listing->comments as below.

override func viewDidLoad() {
        super.viewDidLoad()

        var listing = Listing()

        //Assign listing coredata object according to your values and save it.


        //Fetch above listing comments in array format and use it according to your requirement.

        var listingComments:Array = listing.comments!.allObjects
        let commentFirst:Comment = listingComments[0] as! Comment
        print(commentFirst.commentId)
        print(commentFirst.comment)
        print(commentFirst.rating)
        print(commentFirst.username)
    }   

listingComments is similar to your declared variable 'var comments:[Comment]', You don't require to explicitly write [Comment], you can access of NSSet objects by it's allObjects property and assign it to Array object.

Upvotes: 1

Eendje
Eendje

Reputation: 8883

comments = (listings?.comments.alObjects as! [Comment]) ?? []

This line should do it.

Upvotes: 0

Related Questions