View in English

  • Apple Developer
    • Get Started

    Explore Get Started

    • Overview
    • Learn
    • Apple Developer Program

    Stay Updated

    • Latest News
    • Hello Developer
    • Platforms

    Explore Platforms

    • Apple Platforms
    • iOS
    • iPadOS
    • macOS
    • tvOS
    • visionOS
    • watchOS
    • App Store

    Featured

    • Design
    • Distribution
    • Games
    • Accessories
    • Web
    • Home
    • CarPlay
    • Technologies

    Explore Technologies

    • Overview
    • Xcode
    • Swift
    • SwiftUI

    Featured

    • Accessibility
    • App Intents
    • Apple Intelligence
    • Games
    • Machine Learning & AI
    • Security
    • Xcode Cloud
    • Community

    Explore Community

    • Overview
    • Meet with Apple events
    • Community-driven events
    • Developer Forums
    • Open Source

    Featured

    • WWDC
    • Swift Student Challenge
    • Developer Stories
    • App Store Awards
    • Apple Design Awards
    • Apple Developer Centers
    • Documentation

    Explore Documentation

    • Documentation Library
    • Technology Overviews
    • Sample Code
    • Human Interface Guidelines
    • Videos

    Release Notes

    • Featured Updates
    • iOS
    • iPadOS
    • macOS
    • watchOS
    • visionOS
    • tvOS
    • Xcode
    • Downloads

    Explore Downloads

    • All Downloads
    • Operating Systems
    • Applications
    • Design Resources

    Featured

    • Xcode
    • TestFlight
    • Fonts
    • SF Symbols
    • Icon Composer
    • Support

    Explore Support

    • Overview
    • Help Guides
    • Developer Forums
    • Feedback Assistant
    • Contact Us

    Featured

    • Account Help
    • App Review Guidelines
    • App Store Connect Help
    • Upcoming Requirements
    • Agreements and Guidelines
    • System Status
  • Quick Links

    • Events
    • News
    • Forums
    • Sample Code
    • Videos
 

Vidéos

Ouvrir le menu Fermer le menu
  • Collections
  • Toutes les vidéos
  • À propos

Plus de vidéos

  • À propos
  • Code
  • Create a custom data store with SwiftData

    Combine the power of SwiftData's expressive, declarative modeling API with your own persistence backend. Learn how to build a custom data store and explore how to progressively add persistence features in your app. To get the most out of this session, watch “Meet SwiftData” and “Model your schema with SwiftData” from WWDC23.

    Chapitres

    • 0:00 - Introduction
    • 1:21 - Overview
    • 4:50 - Meet DataStore
    • 7:42 - Example store

    Ressources

    • Forum: Programming Languages
    • SwiftData
      • Vidéo HD
      • Vidéo SD

    Vidéos connexes

    WWDC24

    • Track model changes with SwiftData history
  • Rechercher dans cette vidéo…
    • 8:15 - Implement a JSON store

      // Implement a JSON store
      
      @available(swift 5.9) @available(macOS 15, iOS 18, tvOS 18, watchOS 11, visionOS 2, *)
      final class JSONStoreConfiguration: DataStoreConfiguration {
          typealias StoreType = JSONStore
        
          var name: String
          var schema: Schema?
          var fileURL: URL
      
          init(name: String, schema: Schema? = nil, fileURL: URL) {
              self.name = name
              self.schema = schema
              self.fileURL = fileURL
          }
      
          static func == (lhs: JSONStoreConfiguration, rhs: JSONStoreConfiguration) -> Bool {
              return lhs.name == rhs.name
          }
      
          func hash(into hasher: inout Hasher) {
              hasher.combine(name)
          }
      }
      
      @available(swift 5.9) @available(macOS 15, iOS 18, tvOS 18, watchOS 11, visionOS 2, *)
      final class JSONStore: DataStore {
          typealias Configuration = JSONStoreConfiguration
          typealias Snapshot = DefaultSnapshot
      
          var configuration: JSONStoreConfiguration
          var name: String
          var schema: Schema
          var identifier: String
      
          init(_ configuration: JSONStoreConfiguration, migrationPlan: (any SchemaMigrationPlan.Type)?) throws {
              self.configuration = configuration
              self.name = configuration.name
              self.schema = configuration.schema!
              self.identifier = configuration.fileURL.lastPathComponent
          }
      
          func save(_ request: DataStoreSaveChangesRequest<DefaultSnapshot>) throws -> DataStoreSaveChangesResult<DefaultSnapshot> {
              var remappedIdentifiers = [PersistentIdentifier: PersistentIdentifier]()
              var serializedTrips = try self.read()
      
              for snapshot in request.inserted {
                  let permanentIdentifier = try PersistentIdentifier.identifier(for: identifier, 
                                                                                entityName: snapshot.persistentIdentifier.entityName,
                                                                                primaryKey: UUID())
                  let permanentSnapshot = snapshot.copy(persistentIdentifier: permanentIdentifier)
                  serializedTrips[permanentIdentifier] = permanentSnapshot
                  remappedIdentifiers[snapshot.persistentIdentifier] = permanentIdentifier
              }
      
              for snapshot in request.updated {
                  serializedTrips[snapshot.persistentIdentifier] = snapshot
              }
      
              for snapshot in request.deleted {
                  serializedTrips[snapshot.persistentIdentifier] = nil
              }
            
              try self.write(serializedTrips)
              return DataStoreSaveChangesResult<DefaultSnapshot>(for: self.identifier,
                                                                 remappedPersistentIdentifiers: remappedIdentifiers,
                                                                 deletedIdentifiers: request.deleted.map({ $0.persistentIdentifier }))
          }
      
          func fetch<T>(_ request: DataStoreFetchRequest<T>) throws -> DataStoreFetchResult<T, DefaultSnapshot> where T : PersistentModel {
              if request.descriptor.predicate != nil {
                  throw DataStoreError.preferInMemoryFilter
              } else if request.descriptor.sortBy.count > 0 {
                  throw DataStoreError.preferInMemorySort
              }
      
              let objs = try self.read()
              let snapshots = objs.values.map({ $0 })
              return DataStoreFetchResult(descriptor: request.descriptor, fetchedSnapshots: snapshots, relatedSnapshots: objs)
          }
      
          func read() throws -> [PersistentIdentifier: DefaultSnapshot] {
              if FileManager.default.fileExists(atPath: configuration.fileURL.path(percentEncoded: false)) {
                  let decoder = JSONDecoder()
                  decoder.dateDecodingStrategy = .iso8601
      
                  let trips = try decoder.decode([DefaultSnapshot].self, from: try Data(contentsOf: configuration.fileURL))
                  var result = [PersistentIdentifier: DefaultSnapshot]()
                  trips.forEach { s in
                      result[s.persistentIdentifier] = s
                  }
                  return result
              } else {
                  return [:]
              }
          }
      
          func write(_ trips: [PersistentIdentifier: DefaultSnapshot]) throws {
              let encoder = JSONEncoder()
              encoder.dateEncodingStrategy = .iso8601
              encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
              let jsonData = try encoder.encode(trips.values.map({ $0 }))
              try jsonData.write(to: configuration.fileURL)
          }
      }

Developer Footer

  • Vidéos
  • WWDC24
  • Create a custom data store with SwiftData
  • Open Menu Close Menu
    • iOS
    • iPadOS
    • macOS
    • tvOS
    • visionOS
    • watchOS
    • App Store
    Open Menu Close Menu
    • Swift
    • SwiftUI
    • Swift Playground
    • TestFlight
    • Xcode
    • Xcode Cloud
    • Icon Composer
    • SF Symbols
    Open Menu Close Menu
    • Accessibility
    • Accessories
    • Apple Intelligence
    • Audio & Video
    • Augmented Reality
    • Business
    • Design
    • Distribution
    • Education
    • Games
    • Health & Fitness
    • In-App Purchase
    • Localization
    • Maps & Location
    • Machine Learning & AI
    • Security
    • Safari & Web
    Open Menu Close Menu
    • Documentation
    • Downloads
    • Sample Code
    • Videos
    Open Menu Close Menu
    • Help Guides & Articles
    • Contact Us
    • Forums
    • Feedback & Bug Reporting
    • System Status
    Open Menu Close Menu
    • Apple Developer
    • App Store Connect
    • Certificates, IDs, & Profiles
    • Feedback Assistant
    Open Menu Close Menu
    • Apple Developer Program
    • Apple Developer Enterprise Program
    • App Store Small Business Program
    • MFi Program
    • Mini Apps Partner Program
    • News Partner Program
    • Video Partner Program
    • Security Bounty Program
    • Security Research Device Program
    Open Menu Close Menu
    • Meet with Apple
    • Apple Developer Centers
    • App Store Awards
    • Apple Design Awards
    • Apple Developer Academies
    • WWDC
    Read the latest news.
    Get the Apple Developer app.
    Copyright © 2026 Apple Inc. All rights reserved.
    Terms of Use Privacy Policy Agreements and Guidelines