Tuesday, March 17, 2015

Using Core Data With Swift

Tom Harrington:

Both Core Data and Swift include the concept of an optional value. But when Xcode generates subclasses, it doesn’t consider whether Core Data thinks the value is optional when generating the Swift file. It generates non-optional properties every time. This conflict means that you end up a Swift non-optional property that could reasonably have a nil value. The compiler sees that the property is not optional, so it doesn’t mind that you aren’t checking this (in fact, Swift rules mean it’s not possible to check, because the property is not optional). This is exactly the kind of problem Swift’s compiler is supposed to catch for you, but here it can’t.

This can lead to crashes.

If you’re using mogenerator, you’re covered for Core Data optionals. It makes sure Core Data optionals become Swift optionals. I’d take it a step farther and make all properties optional in Swift even if they’re required by Core Data. Core Data doesn’t enforce the “required” rule until you save changes, so even non-optional attributes can legally be nil at almost any time.


Although the documentation could be read as meaning that @NSManaged is required, it actually isn’t. It’s only needed if you’ll be letting Core Data handle the accessors. If you’re providing your own, drop it. Core Data’s accessor magic is not documented but it seems you can’t just override it like you’d override other methods.

1 Comment RSS · Twitter

[…] Using Core Data With Swift, Generating Core Data Swift, Modern Core Data With Swift, momdec: Core Data Model […]

Leave a Comment