我是 Swift 新手。我正在担心如何实现一个功能。我有一个具有多项选择的 TableView ,如果用户选择和取消选择,则应将其保存在数组中,并将数组中的记录稍后保存到核心数据中。我尝试了很多方法,但它只存储一条记录。
最佳答案
您必须遍历数组中的每条记录并创建一个新的 [NSEntityDescription insertNewObjectForEntityForName] 对象。下面是一个常见方法的示例,它接受 coreDataEntityName 和记录数组。假设您的实体名称是 Record,它具有属性作为名称,那么您可以从数组中设置属性,然后保存上下文。
func insertItems(coreDataTable : String, records: NSArray) -> Bool {
let error: NSError?
for(item in records as NSDictionary!) {
let entity = NSEntityDescription.entityForName(coreDataTable, inManagedObjectContext: self.managedContext)
var record = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) as Record!
record.name = item["name"]
if (!self.mainObjectContext.save()) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
//abort();
return false
}
}
return true
}
这将添加您的所有记录。
关于swift - 如何在核心数据中保存多条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36358061/