0

I am using Core Data in my app and am dealing with a many to many relationship between two entities. My goal is to have the user select which of one entity will be related to another entity by using a tableview and having the user select cells.

When the Class for the Entity is created, "Lists" is set as type NSSet which makes sense since it doesn't need to be ordered, and I don't want more than one of any other entity in there.

My problem comes when I want to add items to an NSSet, I cannot do it as far as I know without using a NSMutableSet. Then I gain addObject and removeObject. I can get everything to work except the part where I initialize the NSMutableSet to have everything that the "Lists" NSSet currently has. Everything I've tried either tells me it will always fail and won't build, or ends up returning nil unexpectedly and errors out.

So is there a way to correctly change the contents of a NSSet or at least cast a NSSet into a NSMutableSet and then when I'm done, cast that NSMutableSet back into a NSSet?

I can add some of my code if necessary, but I think I explained it pretty well. Let me know and I'll add whatever details you need.

Thank you in advance.

Wain
  • 118,658
  • 15
  • 128
  • 151
Jason Brady
  • 1,560
  • 1
  • 17
  • 40

2 Answers2

2

simply create a mutable copy:

var set = NSSet(objects: "One", "Two", "Three")
let mutableSet = set.mutableCopy() as! NSMutableSet
mutableSet.addObject("Four")
set = mutableSet
André Slotta
  • 13,774
  • 2
  • 22
  • 34
  • 3
    this answer is not appropriate for core data – Wain Jun 21 '16 at 20:51
  • ok, sorry. "So is there a way to correctly change the contents of a NSSet or at least cast a NSSet into a NSMutableSet and then when I'm done, cast that NSMutableSet back into a NSSet?" sounded to me like there is a general problem in casting the types... – André Slotta Jun 21 '16 at 20:53
  • Man, I knew it was simple like that. Thank you so much. It seems to work! – Jason Brady Jun 21 '16 at 20:54
  • well @Wain... seems like that was the answer he expected... :) – André Slotta Jun 21 '16 at 20:55
  • @JasonBrady: glad i could help. :) – André Slotta Jun 21 '16 at 20:55
  • Wain, I know about the @NSManaged func addCatalogObject(catalog: Catalog) features within the CoreData Class. But I'm wanting the user to be able to select the "Lists" from the tableview, then create a string on a previous viewcontroller that shows what was selected. There is a cancel option here, so I don't actually want to set the Entity Lists until after the user hits save on the new screen. This is when I'd be setting the Entity Lists equal to the NSSet created previously. – Jason Brady Jun 21 '16 at 20:58
0

mutableCopy()

Call mutableCopy() on your NSSet:

let x = NSSet()
let y = x.mutableCopy() //returns NSMutableSet
Alexander
  • 59,041
  • 12
  • 98
  • 151