ytpm
ytpm

Reputation: 5150

Copy array of NSManagedObject objects in Swift 4

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];

Upvotes: 0

Views: 323

Answers (1)

rmaddy
rmaddy

Reputation: 318824

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.

Upvotes: 1

Related Questions