在 Swift 4 中复制 NSManagedObject 对象数组
Copy array of NSManagedObject objects in Swift 4
我有一个 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];
要将 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
是否完全适用于(Objective-C 或 Swift)NSManagedObject
是另一个问题。请参阅 How can I duplicate, or copy a Core Data Managed Object? 及其 Swift 答案以获取专门涵盖对 NSManagedObject
实例进行深度复制的代码。
我有一个 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];
要将 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
是否完全适用于(Objective-C 或 Swift)NSManagedObject
是另一个问题。请参阅 How can I duplicate, or copy a Core Data Managed Object? 及其 Swift 答案以获取专门涵盖对 NSManagedObject
实例进行深度复制的代码。