8

How do you set the default value of a UUID attribute in the core data xcdatamodel. if I set the attribute as non-optional it requires a default value. in code I'd set it using UUID() to assign a value but this doesn't work in the xcdatamodel

ngb
  • 821
  • 9
  • 21

3 Answers3

2

You can use a string representation of any UUID() value as a default. For example: 0CF044A3-333C-4B22-8FEB-F68B004B6C96 could be a default.

To quickly generate a new UUID a terminal could be used. Just type swift repl there and then import Foundation and then print(UUID()). This will give you a new random UUID.

Default UUID in CoreData

Denis
  • 3,167
  • 1
  • 22
  • 23
0

It's not necessary to assign a default value in the model.

In the class override awakeFromInsert

override func awakeFromInsert() {
    super.awakeFromInsert()
    uuid = UUID()
} 
vadian
  • 274,689
  • 30
  • 353
  • 361
  • 3
    This doesn't solve the problem for me as I get error in the xcdatamodel that the field needs a default value. Unable to set a default value for UUID. – Domnic Francis Apr 19 '21 at 10:40
  • Very strange. I'm using this way in a few projects. Did you declare the type of the attribute as UUID? – vadian Apr 19 '21 at 12:13
  • 1
    It's hard to tell exactly if it is required or not. I believe that it IS required, at least according to Xcode reports, WHEN using CloudKit. – Xials Jun 01 '21 at 16:50
  • When using CloudKit, this crashes if not Optional. This answer does not seem to work. I have fallen back to changing my id types to Strings and using `UUID().uuidString` then they can just have an empty string default value in the Attributes inspector. – rbaldwin Jun 25 '21 at 09:49
  • 1
    rbaldwin - CloudKit and CoreData require all attributes to be optional. this function sets the UUID so its always populated. You shouldnt untick the Optional box in your xcdatamodel ever. I'm surprised you even got it to compile. Set your uuid attribute to optional and put the awakeFromInsert function in your ManagedObject Class file for the relevant entity. – ngb Oct 09 '21 at 12:38
-7

Please satisfy the Identifiable protocol to get the UUID() work.