在Swift 4中复制NSManagedObject对象的数组

时间:2019-05-01 15:51:52

标签: arrays swift core-data copy swift4

我有一个NSManagedObject's数组,我想将它们复制到一个新数组中以操作它们,并且在用户完成操作后不保存更改。

数组:

var origQuestions: [Questions]?

这是我从CoreData中检索数据的方式:

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

这是我在Objective-C中需要的,但是我想知道如何在Swift 4中做到这一点:

NSMutableArray *questionsCopy = [[NSMutableArray alloc] initWithArray:self.origQuestions copyItems:YES];

1 个答案:

答案 0 :(得分:1)

要将该Objective-C代码转换为Swift,请执行以下操作:

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

但是由于您将origQuestions声明为可选,所以它必须是:

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

NSManagedObject是否完全兼容(Objective-C或Swift)是另一个问题。有关专门涵盖制作NSManagedObject实例的深层副本的代码,请参见How can I duplicate, or copy a Core Data Managed Object?及其Swift答案。