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
Asked
Active
Viewed 4,311 times
3 Answers
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.

Denis
- 3,167
- 1
- 22
- 23
-
The command is now `swift repl` (not just simply `swift`) to get a fast UUID. – iSpain17 Feb 18 '23 at 12:11
-
This answer reminds me of the classic xkcd comic: `func getRandomNumber() -> { return 4 // Chosen by fair dice row, guaranteed to be random }` https://xkcd.com/221/ – Nikolay Suvandzhiev Apr 07 '23 at 07:21
-
That's because it's a requirement to provide a constant here as a default value isn't it? – Denis Apr 11 '23 at 14:34
-
The answer has been updated to use `swift repl`. – Denis Jun 29 '23 at 16:17
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
-
3This 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
-
1It'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
-
1rbaldwin - 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