【发布时间】:2017-10-14 00:11:06
【问题描述】:
我一直在寻找一些关于如何在 Core Data 中存储 NSArray 的示例代码,但没有任何运气。我现在知道如何存储 NSStrings、NSDate 和其他类型的数据,但很难存储 NSArray。我读过很多文章说你必须将它写入磁盘并写入文件,但我似乎无法理解。
import UIKit
class Person: NSObject {
var fullName : String!
var mobileNumbers : [Mobile]!
}
import UIKit
class Mobile: NSObject {
var mobileNumber : String!
}
// core data save method
以下方法显示保存到核心数据
func save(name: Person) {
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
var managedContext = NSManagedObjectContext()
if #available(iOS 10.0, *) {
managedContext = appDelegate.persistentContainer.viewContext
} else {
// Fallback on earlier versions
}
let entity = NSEntityDescription.entity(forEntityName: "Contact",in: managedContext)!
let person = NSManagedObject(entity: entity,insertInto: managedContext)
person.setValue(name.fullName, forKeyPath: "fullName")
if let mob = name.mobileNumberList{
let arch = NSKeyedArchiver.archivedData(withRootObject: mob[0])
print(arch)
person.setValue(arch, forKey: "mobileNumberList")
}
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
【问题讨论】:
-
coredata 没有使用 Archiver,而是提供了一种称为 Transformable 的选项数据类型。您可以在您的实体中将您的数据类型设置为可转换的。在此链接上查看我的答案stackoverflow.com/questions/8682324/…replace dictionary with array type
-
对于
mobileNumberList属性,您似乎已经有了执行此操作的代码。它不工作吗?如果没有,具体出了什么问题?
标签: ios swift core-data binary-data