UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Should the .externalStorage attribute work with a SwiftData model property that is an array of optional data?

Forums > SwiftUI

In my SwiftData model I have a property that is an optional array of images stored as data.

I thought by using the syntax @Attribute(.externalStorage) var imagesData: [Data]? the data would be stored external to the SwiftData database. It is not. I have inspected the containing entity (using the Core Data Lab app) and have observed the data is not stored externally.

Am I using the correct syntax?

I have confirmed with a property that is not an array (@Attribute(.externalStorage) var imagesData: Data?) that its data is stored externally as expected.

What is the correct approach when trying to saving an array of images within a SwiftData entity?

@Model class Item {
   var text: String = ""
   var date: Date = Date.now

   @Attribute(.externalStorage) var imagesData: [Data]?

   init(text: String, date: Date) {
      self.text = text
      self.date = date
   }

2      

I am assuming the answer to my question above is "no" and I used an incorrect data model.

I updated my project to add an additional model for PhotoData as shown below. This seems to work and does feel like a better approach. Not to mention, it works. Posting this followup in case others, like me, new to some of these concepts are tripping on the same and find this thread.


@Model class Item {
   var text: String = ""
   var date: Date = Date.now

   @Relationship(deleteRule: .cascade, inverse: \PhotoData.item) var photosData: [PhotoData]? = [PhotoData]()

   init(text: String, date: Date) {
      self.text = text
      self.date = date
   }
}

@Model class PhotoData {
   var id: UUID = UUID()
   @Attribute(.externalStorage) var photoData: Data?

   @Relationship(deleteRule: .nullify) var item: Item?

   init(photoData: Data) {
      self.id = UUID()
      self.photoData = photoData
   }
}

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.