UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Adding an Array of Objects to an NSSet Relationship

Forums > SwiftUI

Hey All, this is a continuation to my previous post about Many to Many Relationships in Core Data. I wanted to elaborate further and update you all with my current problem, hoping someone might be able to help me get over this current stump.

I will attach bellow the code blocks to support this thread.

extension Item {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Item> {
        return NSFetchRequest<Item>(entityName: "Item")
    }
    @NSManaged public var id: UUID?
    @NSManaged public var name_: String?
    @NSManaged public var trips_: NSSet?
 }

 extension Trip {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Trip> {
        return NSFetchRequest<Trip>(entityName: "Trip")
    }

    @NSManaged public var id: UUID?
    @NSManaged public var name_: String?
    @NSManaged public var items_: NSSet?
}

Above you can see the two NSManagedObject Classes. Both with an optional NSSet properties.

Again the task here is to allow multiple Items belong to Multiple Trips, and each Trip have Multiple Items.

Now in the following lines of code you will see I have created a temporary array that fills when you select an Item from a list.


@State private var itemsChecked = [Item]()

   // The purpose of this function is to add the selected item to our temporary array itemsChecked
    func handleItemSelected(_ item: Item) {
        if !itemsChecked.contains(item) {

            // put the item into our list of what's about to be added to Trips
            itemsChecked.append(item)
        }
    }

    // The purpose of this function is to remove the selected item from our temporary array itemsChecked
    func handleItemUnSelected(_ item: Item) {
        self.itemsChecked.removeAll{$0.id == item.id}
    }

Now to where I am stuck, I have this array itemsChecked, that is an array of the selected items and I want to then take that array and add each item in the array to the relationship under trip.

Again in the end I would like each item to know which trips it is in, as well as each trip having multiple items, that may exist in other trips. Hence the reason for the two NSSets.

Any advice about how to implement this would be much apprcieated!

2      

I have attempted something like this to no avail.

I know I must use some sort of ForEach statement to go through each item in the array and then do something.

However I'm just stumpped.

2      

For one thing, you can't use ForEach inside a function; it is a SwiftUI View and can only be used within a ViewBuilder, such as the body property of a View struct. You would need to do this instead:

for item in itemsChecked { 
    //do whatever with item
}

You can insert an array into an NSSet without a loop like this:

let set1 = NSSet(array: [1,2,3,4,5,6,7,8,9,0])
let array1 = [1,12,3,13,23]
let set2 = set1.addingObjects(from: array1)

Or if you used NSMutableSet instead of NSSet:

let set1 = NSMutableSet(array: [1,2,3,4,5,6,7,8,9,0])
let array1 = [1,12,3,13,23]
set1.addObjects(from: array1)

However, since NSSet is typeless (i.e., the element is Any), you might want to use Set<Item> instead, in which case you could do something like this:

let set3: Set<Int> = [1,2,3,4,5,6,7,8,9,0]
let array2 = [1,12,3,13,23]
let set4 = set3.union(array2)

5      

hi,

use the generated accessor for Core Data for a given var trip: Trip:

for item in itemsChecked {
    trip.addToItems_(item)
}

hope that helps,

DMG

3      

I will give this a try, thank you both so much!

Also for anyone reading this forum later on, experenicing the same issues, I have found a really great video describing core data relationships with a real SwiftUI example, also covering Many To Many relationships.

https://www.youtube.com/watch?v=huRKU-TAD3g&t=967s

Hope this helps anyone down the road.

Many thanks to you all.

Happy Swifting!

Luke

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.