TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Array of Strings in Core Data

Forums > SwiftUI

I want to create an array of strings in core data, but there's no option for an array.

3      

hi,

"arrays" in Core Data are often implemented using relationships, but there is another option.

let' suppose you want some entity X to have an associated Set of Strings.

option 1: create a new Entity in Core Data to represent a single String. example:

entity name: StringHolder with just one attribute string: String?.

then add a relationship between X and StringHolder that is one-to-many (many strings related to one X).

you'll get an NSSet of StringHolder objects associated with each X. with proper type casting you can access the StringHolder objects associated with that X and extract the strings they represent into an [String].

option 2: X has a Transformable attribute named strings whose Custom Class is marked in the Core Data model as [String]. (be sure you set the Transformer entry to NSSecureUnarchiveFromDataTransformer.)

which path you pick depends on

  • do you want to search for strings in Core Data? if so, use option 1 (transformable attributes are not directly searchable uisng a fetch request in Core Data).
  • do you want the strings ordered in a certain way that cannot be accomplished with a simple "sort" of a Set in your code?. if so, option 1 will let you mark the relationship as "Ordered," which will give you an NSOrderedSet in your code. you may have to use Xcode-generated accessors to manipulate that NSOrderedSet.
  • do you want the Core Data data store to live in the cloud (using NSPersistentCloudKitContaner)? if so, the cloud does not support ordered relationships with one-to-many, so you would have to use option 1.

hope that helps,

DMG

5      

Thank you for your help. Option 1 seems to be the best option for me than.

3      

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!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.