0

I have an array of NSManagedObject's and I want to copy them to a new array in order to manipulate them and not save the changes after the user is done.

The array:

var origQuestions: [Questions]?

This is how I retreive the data from CoreData:

self.origQuestions = MainDb.sharedInstance.randomQuestions(entity: "Questions", count: self.questionToShow)

This is what I need in Objective-C, but I want to know how to do so in Swift 4:

NSMutableArray *questionsCopy = [[NSMutableArray alloc] initWithArray:self.origQuestions copyItems:YES];
ytpm
  • 4,962
  • 6
  • 56
  • 113

1 Answers1

1

To translate that Objective-C code into Swift you do:

var questionsCopy = NSArray(array: origQuestions, copyItems:true) as! [Questions]

But since you declared origQuestions as optional, it needs to be:

var questionsCopy = origQuestions != nil ? NSArray(array: origQuestions!, copyItems:true) as? [Questions] : nil

Whether that fully works (Objective-C or Swift) with NSManagedObject or not is another question. See How can I duplicate, or copy a Core Data Managed Object? and its Swift answers for code that specifically covers doing deep copies of NSManagedObject instances.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • I actually used the link to the question you gave in your answer, found there an approach with Swift 4. Great answer! Thanks. https://stackoverflow.com/a/51544796/1138498 – ytpm May 02 '19 at 22:18
  • Out of curiosity, why did you originally want that Objective-C line? And did you try it in Swift after translating it as shown in my answer and what was the result? – rmaddy May 02 '19 at 22:20
  • I didn't want that Obj-C line. I was just trying to show how I used to do it in Obj-C and didn't know how to do so in Swift. Because in Swift you need to clone the array differently I guess. – ytpm May 02 '19 at 22:54