Last active
January 22, 2024 01:15
-
-
Save benigumocom/7f56dc90605523480202ea5435a8419d to your computer and use it in GitHub Desktop.
【 #SwiftData 】ModelContainer の View へのセット 👉 https://android.benigumo.com/20240122/modelcontainer/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import SwiftData | |
struct BackyardBirdsDataContainerViewModifier: ViewModifier { | |
let container: ModelContainer | |
init(inMemory: Bool) { | |
container = try! ModelContainer(for: DataGeneration.schema, configurations: [ModelConfiguration(isStoredInMemoryOnly: inMemory)]) | |
} | |
func body(content: Content) -> some View { | |
content | |
.generateData() | |
.modelContainer(container) | |
} | |
} | |
struct GenerateDataViewModifier: ViewModifier { | |
@Environment(\.modelContext) private var modelContext | |
func body(content: Content) -> some View { | |
content.onAppear { | |
DataGeneration.generateAllData(modelContext: modelContext) | |
} | |
} | |
} | |
public extension View { | |
func backyardBirdsDataContainer(inMemory: Bool = DataGenerationOptions.inMemoryPersistence) -> some View { | |
modifier(BackyardBirdsDataContainerViewModifier(inMemory: inMemory)) | |
} | |
} | |
fileprivate extension View { | |
func generateData() -> some View { | |
modifier(GenerateDataViewModifier()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment