текущая настройка < /h3>
Текущий @model < /code>, что довольно проста по стандартам Swiftdata, за исключением того, что у нее есть гораздо больше свойств, чем я включал здесь: < /p>
Код: Выделить всё
@Model
final class MyData
{
var property1: Bool = true
var property2: Bool = true
var property3: Int = 1
// And many more properties...
// Default init.
init()
{
// Assign default values to properties.
self.property1 = true
self.property2 = true
self.property3 = 1
// ...
}
// Dynamic init.
init(
property1: Bool,
property2: Bool,
property3: Int
)
{
self.property1 = property1
self.property2 = property2
self.property3 = property3
// ...
}
}
Код: Выделить всё
var sharedModelContainer: ModelContainer =
{
let schema = Schema(
[
MyData.self,
])
let modelConfiguration = ModelConfiguration(
schema: schema,
isStoredInMemoryOnly: false
)
do
{
return try ModelContainer(
for: schema,
configurations: [modelConfiguration]
)
}
catch
{
fatalError("Could not create ModelContainer: \(error)")
}
}()
@main
struct myApp: App
{
var body: some Scene
{
WindowGroup
{
ContentView()
}
.modelContainer(sharedModelContainer)
}
}
< /code>
Попытка миграции < /h3>
Чтобы начать реализацию миграции, я переименовал модель, чтобы отразить его версию: < /p>
@Model
final class MyDataV1
{
// No other changes compared to the code shared above.
}
Код: Выделить всё
@Model
final class MyDataV2
{
// Changed to an array.
var property1: [Bool] = [true]
var property2: Bool = true
var property3: Int = 1
// And many more properties...
// Migration init.
init(
myDataV1: MyDataV1
)
{
// Convert to an array.
self.property1 = [myDataV1.property1]
self.property2 = myDataV1.property2
self.property3 = myDataV1.property3
// ...
}
// Default init.
init()
{
// Assign default values to properties.
self.property1 = [true]
self.property2 = true
self.property3 = 1
// ...
}
// Dynamic init.
init(
property1: [Bool],
property2: Bool,
property3: Int
)
{
self.property1 = property1
self.property2 = property2
self.property3 = property3
// ...
}
}
Код: Выделить всё
typealias MyData = MyDataV2
Код: Выделить всё
enum MyDataSchemaV1: VersionedSchema
{
static var versionIdentifier: Schema.Version = Schema.Version(1, 0, 0)
static var models: [any PersistentModel.Type]
{
[MyDataV1.self]
}
}
enum MyDataSchemaV2: VersionedSchema
{
static var versionIdentifier: Schema.Version = Schema.Version(2, 0, 0)
static var models: [any PersistentModel.Type]
{
[MyDataV2.self]
}
}
Код: Выделить всё
enum MyDataMigrationPlan: SchemaMigrationPlan
{
static var schemas: [any VersionedSchema.Type]
{
[MyDataSchemaV1.self, MyDataSchemaV2.self]
}
static var stages: [MigrationStage]
{
[migrateFromV1ToV2]
}
private static var migrationFromV1ToV2Data: [MyDataV1] = []
static let migrateFromV1ToV2 = MigrationStage.custom(
fromVersion: MyDataSchemaV1.self,
toVersion: MyDataSchemaV2.self,
willMigrate:
{
modelContext in
let descriptor : FetchDescriptor = FetchDescriptor()
let v1Data : [MyDataV1] = try modelContext.fetch(descriptor)
migrationFromV1ToV2Data = v1Data
try modelContext.delete(model: MyDataV1.self)
try modelContext.save()
},
didMigrate:
{
modelContext in
migrationFromV1ToV2Data.forEach
{
myDataV1 in
let myDataV2 = MyDataV2(myDataV1: myDataV1)
modelContext.insert(myDataV2)
}
try modelContext.save()
}
)
}
Код: Выделить всё
var sharedModelContainer: ModelContainer =
{
let schema = Schema(
[
MyData.self,
])
let modelConfiguration = ModelConfiguration(
schema: schema,
isStoredInMemoryOnly: false
)
do
{
return try ModelContainer(
for: schema,
migrationPlan: MyDataMigrationPlan.self,
configurations: [modelConfiguration]
)
}
catch
{
fatalError("Could not create ModelContainer: \(error)")
}
}()
< /code>
ошибки миграции < /h3>
Я создал ситуацию, в которой экземпляр mydatav1 < /code> уже был сохранен в SwiftData, а затем я реализовал изменения выше и запустил новую версию. < /p>
я добавил в Mogrationplan. Willmigrate
Код: Выделить всё
CoreData: error: Error: Persistent History (3178) has to be truncated due to the following entities being removed: (
MyDataV1
)
CoreData: warning: Warning: Dropping Indexes for Persistent History
CoreData: warning: Warning: Dropping Transactions prior to 3178 for Persistent History
CoreData: warning: Warning: Dropping Changes prior to TransactionID 3178 for Persistent History
CoreData: error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134060)
CoreData: error: userInfo:
CoreData: error: NSLocalizedFailureReason : Instances of NSCloudKitMirroringDelegate are not reusable and should have a lifecycle tied to a given instance of NSPersistentStore.
CoreData: error: storeType: SQLite
CoreData: error: configuration: default
< /code>
попытка решения 1 < /h3>
Я думал, что это может быть потому, что в Willmigrate < /code> я звонил следующее: < /p>
< /p>
Подробнее здесь: [url]https://stackoverflow.com/questions/79536880/swiftdata-custom-migration-always-fails-possible-bug-in-swiftdata[/url]