介绍
- Core Data 的继承者,使用声明式的语法进行数据的持久化操作。
- 支持 CloudKit 同步,并且与 Core Data 兼容。
使用步骤
- 导入模块
import SwiftData
。
- 使用
@Model
修饰模型。
- 将模型注册到
ModelContainer
。
- 获取模型上下文
ModelContext
。
- 通过模型上下文进行增删改查(CRUD)操作。
案例
import Foundation
import SwiftData
import UIKit
@Model
class User: CustomStringConvertible {
var id: UUID
var name: String
var company: Company
init(name: String, company: Company) {
id = UUID()
self.name = name
self.company = company
}
var description: String {
return "\(name)—\(company.name)—\(company.address)"
}
}
@Model
class Company {
@Attribute(.unique)
var id: String
var name: String
var address: String
init(id: String, name: String, address: String) {
self.id = id
self.name = name
self.address = address
}
}
class DataTools {
static var shared = DataTools()
var container: ModelContainer?
var context: ModelContext?
init() {
do {
container = try ModelContainer(for: [User.self, Company.self])
if let container {
context = ModelContext(container)
}
} catch {
print(error)
}
}
// 增加
func insert(user: User) {
context?.insert(object: user)
}
// 删除
func delete(user: User) {
context?.delete(object: user)
}
// 修改
func update(user: User, newCompanyName: String, newCompanyAddress: String) {
user.company.name = newCompanyName
user.company.address = newCompanyAddress
}
// 查询
func select(completionHandler: @escaping ([User]?, Error?) -> Void) {
let descriptor = FetchDescriptor<User>(sortBy: [SortDescriptor<User>(\.name)])
do {
let data = try context?.fetch(descriptor)
completionHandler(data, nil)
} catch {
completionHandler(nil, error)
}
}
// 保存
func save() {
do {
try context?.save()
} catch {
print(error.localizedDescription)
}
}
}
class ViewController: UIViewController {
var dataTools = DataTools.shared
var users = [User]()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func insertData(_ sender: Any) {
let user1 = User(name: "张三", company: Company(id: "1", name: "百度", address: "中国北京"))
let user2 = User(name: "李四", company: Company(id: "2", name: "阿里巴巴", address: "浙江杭州"))
let user3 = User(name: "王五", company: Company(id: "3", name: "腾讯", address: "广东深圳"))
dataTools.insert(user: user1)
dataTools.insert(user: user2)
dataTools.insert(user: user3)
}
@IBAction func deleteData(_ sender: Any) {
if let user = users.last {
dataTools.delete(user: user)
}
}
@IBAction func updateData(_ sender: Any) {
if let user = users.first {
dataTools.update(user: user, newCompanyName: "美团", newCompanyAddress: "中国北京")
}
}
@IBAction func selectData(_ sender: Any) {
dataTools.select { data, error in
if let error {
print(error)
}
if let data {
self.users = data
print(self.users)
}
}
}
}