示例工程 43-coredata-migration
43-coredata-migration/Sources/Ch43Demo/App.swift
import AppKit
import Ch43Kit
import SwiftUI
@main
struct Ch43Demo {
@MainActor
static func main() {
do {
let container = try CoreDataLibrary.makeContainer()
let context = container.viewContext
CoreDataLibrary.insert(title: "B", author: "y", in: context)
CoreDataLibrary.insert(title: "A", author: "x", in: context)
try context.save()
let books = try CoreDataLibrary.fetch(in: context)
print("[43.1] 书籍数量 = \(books.count)")
print("[43.2] 排序后标题 = \(books.map(\.title).joined(separator: ","))")
try CoreDataLibrary.deleteAll(in: context)
try context.save()
print("[43.3] 清空后数量 = \(try CoreDataLibrary.fetch(in: context).count)")
} catch {
print("[43.0] Core Data 失败 = \(error)")
}
print("[43.4] 映射条目 = \(Mapping.rows.count)")
print("[43.5] 板渲染 = \(size(MigrationBoard()))")
print("[43.6] MemoryLayout<MappingRow> = \(MemoryLayout<MappingRow>.size) 字节")
if let directory = ProcessInfo.processInfo.environment["SHOTS_DIR"] {
write(MigrationBoard(), name: "migration-board.png", directory: directory)
}
}
@MainActor
private static func size(_ view: some View) -> String {
guard let image = ImageRenderer(content: view).cgImage else { return "nil" }
return "\(image.width)x\(image.height)"
}
@MainActor
private static func write(_ view: some View, name: String, directory: String) {
let renderer = ImageRenderer(content: view)
renderer.scale = 2
guard
let image = renderer.cgImage,
let data = NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:])
else {
print("[43.7] 截图失败:\(name)")
return
}
let url = URL(fileURLWithPath: directory).appendingPathComponent(name)
do {
try FileManager.default.createDirectory(
at: url.deletingLastPathComponent(),
withIntermediateDirectories: true
)
try data.write(to: url)
print("[43.7] 截图 = \(name) \(image.width)x\(image.height)")
} catch {
print("[43.7] 截图失败:\(error)")
}
}
}