Codable With Core Data and NSManagedObject
Codable With Core Data and NSManagedObject
and NSManagedObject
Published on: August 3, 2020
CODABLE CORE DATA SWIFT
If you've ever wanted to decode a bunch of JSON data into
NSManagedObject instances you've probably noticed that this isn't a
straightforward exercise. With plain structs, you can conform your
struct to Codable and you convert the struct from and to JSON data
automatically.
<img src="https://www.donnywals.com/wp-content/uploads/
RevenueCatLogo.png">
In-app purchases made easy. RevenueCat provides everything you need to
implement, manage, and analyze in-app purchases without managing servers
or writing backend code.
This sponsored message helps keep the content on this site free. Please check
out this sponsor as it directly supports me and this site.
In this week's post, you will learn how you can manually de ne your
managed object subclass and add support for Swift's JSON
fi
fi
fi
fi
fi
fi
decoding and encoding features by conforming your managed
object to Decodable and Encodable. First, I'll explain how you can
tweak automatic class generation and de ne your managed object
subclasses manually while still generating the de nition for all of
your entity's properties.
After that, I'll show you how to conform your managed object to
Decodable, and lastly, we'll add conformance for Encodable as well to
make your managed object conform to the Codable protocol (which
is a combined protocol of Decodable and Encodable).
Open your xcdatamodeld le and select the entity that you want to
manually de ne the managed object subclass for. In the sidebar on
the right, activate the Data model inspector and set the Codegen
dropdown to Category/Extension. Make sure that you set Module to
Current product module and that Name is set to the name of the
managed object subclass that you will de ne. Usually, this class
name mirrors the name of your entity (but it doesn't have to).
<img src="https://
www.donnywals.com/wp-content/uploads/Screen-Shot-2020-08-03-
at-10.09.16.png" alt="" />
fi
fi
fi
fi
fi
fi
After setting up your data model, you can de ne your subclasses.
Since Xcode will generate an extension that contains all of the
managed properties for your entity, you only have to de ne the
classes that Xcode should extend:
Conforming an NSManagedObject to
Decodable
The Decodable protocol is used to convert JSON data into Swift
objects. When your objects are relatively simple and closely mirror
the structure of your JSON, you can conform the object to Decodable
and the Swift compiler generates all the required decoding code for
you.
Unfortunately, Swift can't generate this code for you when you want
to make your managed object conform to Decodable.
extension CodingUserInfoKey {
static let managedObjectContext =
CodingUserInfoKey(rawValue:
"managedObjectContext")!
}
We can use this key to set and get a managed object context from
the userInfo dictionary. Now let's create a JSONDecoder and set its
userInfo dictionary:
self.init(context: context)
Note that Core Data still uses Objective-C under the hood so you
might have to cast some Swift types to their Objective-C
counterparts like I had to with my Set<TodoCompletion>.
self.init(context: context)
If you want to test this code, you can use the following JSON as a
starting point:
[
{
"id": 0,
"label": "Item 0",
"completions": []
},
{
"id": 1,
"label": "Item 1",
"completions": [
{
"completionDate": 767645378
}
]
}
]
Unfortunately, it takes quite a bunch of code to make Decodable
work with managed objects, but the nal solution is something I'm
not too unhappy with. I like how easy it is to use once set up
properly.
In Summary
In this week's post, you learned how you can add support for
Codable to your managed objects by changing Xcode's default code
generation for Core Data entities, allowing you to write your own
class de nitions. You also saw how you can associate a managed
object context with a JSONDecoder through its userInfo dictionary,
allowing you to decode your managed objects directly from JSON
without any extra steps. To wrap up, you saw how to add Encodable
support, making your managed object conform to Codable rather
than just Decodable.
fi