The accepted answer by Martin R
will work.
However it appears that this is part of the default implementation of @NSManaged
properties by Apple.
I tested it like so:
- I created a new Xcode project with Core Data and made a single Entity called
Hello
.
- It has a single attribute called
short
which is saved as an Integer 16
.
- Marked Codegen as
Manual/None
- Created the manual class file for
Hello
as follows:
class Hello: NSManagedObject {
@NSManaged var short : UInt16
}
You'll notice that I've typed it as an unsigned UInt16
.
In my AppDelegate:
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Get Context
let context = self.persistentContainer.viewContext
// Create Test Objects
let hello1 = Hello(entity: Hello.entity(), insertInto: context)
hello1.short = 255
let hello2 = Hello(entity: Hello.entity(), insertInto: context)
hello2.short = 266 // Should overflow Int16
let hello3 = Hello(entity: Hello.entity(), insertInto: context)
hello3.short = 65535 // Should overflow Int16 by a lot
// Save them to the database
do {
try context.save()
} catch {
print(error)
}
// Fetch the save objects
let fetch = NSFetchRequest<Hello>(entityName: "Hello")
if let results = try? context.fetch(fetch) {
for result in results {
print(result.short)
}
}
}
This prints out the following:
255
266
65535
Which I imagine is what someone would want from saving unsigned ints in Core Data.