将对象数组保存到 Core Data
Posted
技术标签:
【中文标题】将对象数组保存到 Core Data【英文标题】:Saving an array of objects to Core Data 【发布时间】:2018-03-09 14:21:35 【问题描述】:我有一个 [User] 类型的数组,我想将它保存在 Core Data 中,然后在表格视图中显示它。以下是我保存和检索数据的函数:
func saveUserData(_ users: [User])
let context = appDelegate.persistentContainer.viewContext
let newUser = NSEntityDescription.insertNewObject(forEntityName: "Users", into: context)
for user in users
newUser.setValue(user.id, forKey: "id")
newUser.setValue(user.name, forKey: "name")
newUser.setValue(user.email, forKey: "email")
newUser.setValue(user.phone, forKey: "phone")
newUser.setValue(user.website, forKey: "website")
newUser.setValue(user.city, forKey: "city")
newUser.setValue(user.lat, forKey: "lat")
newUser.setValue(user.long, forKey: "long")
do
try context.save()
print("Success")
catch
print("Error saving: \(error)")
func retrieveSavedUsers() -> [User]?
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.returnsObjectsAsFaults = false
var retrievedUsers: [User] = []
do
let results = try context.fetch(request)
if !results.isEmpty
for result in results as! [NSManagedObject]
guard let id = result.value(forKey: "id") as? Int else return nil
guard let name = result.value(forKey: "name") as? String else return nil
guard let email = result.value(forKey: "email") as? String else return nil
guard let phone = result.value(forKey: "phone") as? String else return nil
guard let website = result.value(forKey: "website") as? String else return nil
guard let city = result.value(forKey: "city") as? String else return nil
guard let lat = result.value(forKey: "lat") as? String else return nil
guard let long = result.value(forKey: "long") as? String else return nil
let user = User(with: id, name: name, email: email, phone: phone, website: website, city: city, lat: lat, long: long)
retrievedUsers.append(user)
catch
print("Error retrieving: \(error)")
return retrievedUsers
检索工作正常,但问题是它只保存了 Core Data 中最后一个 User 类型的对象。似乎当我在保存用户时迭代用户时,每次迭代都会覆盖用户对象而不是保存一个新对象。知道如何解决这个问题,或者有没有更好的方法将自定义对象数组保存到 Core Data 中?
【问题讨论】:
很好的答案,我想问一下,“User”类型是声明为普通类还是NSManagedObject? @bellaGU 用户定义如下class User: Mappable
【参考方案1】:
您只创建一个用户实体,然后每次都对其进行重写。问题是,就在您遍历用户数组之前,您创建了一个新实体。 您应该为数组中的每个用户都这样做。这是一个非常简单的解决方法,只需交换两行。正确代码见下:
func saveUserData(_ users: [User])
let context = appDelegate.persistentContainer.viewContext
for user in users
let newUser = NSEntityDescription.insertNewObject(forEntityName: "Users", into: context)
newUser.setValue(user.id, forKey: "id")
newUser.setValue(user.name, forKey: "name")
newUser.setValue(user.email, forKey: "email")
newUser.setValue(user.phone, forKey: "phone")
newUser.setValue(user.website, forKey: "website")
newUser.setValue(user.city, forKey: "city")
newUser.setValue(user.lat, forKey: "lat")
newUser.setValue(user.long, forKey: "long")
do
try context.save()
print("Success")
catch
print("Error saving: \(error)")
【讨论】:
以上是关于将对象数组保存到 Core Data的主要内容,如果未能解决你的问题,请参考以下文章
使用 Magical Record 将对象数组插入 Core Data
如何在 Swift 中将字符串数组保存到 Core Data