Remove CoreData boilerplate using protocol.

Arul murugan
1 min readDec 19, 2021

--

While using coreData we can see some amount of repetitive code on every CoreDataTypes during insert, fetch, update, and deleting entities. In this article, we’ll see how to remove that boilerplate code by using protocols.

We have a protocol CoreDataStorable which has associatedtype CoreDataType which should be the type of NSManagedObject(Our entityType). CoreDataStorable protocol’s extension has common methods like insert, fetch, update, delete entities.

Let assume, we have articleListScreen which shows list of articles by implementing CoreDataStorable.

We just mentioned that CoreDataType as Article. That’s it, we can invoke all the methods, implementations will be handled under the protocol extension. We can perform all the operations in a fully type safe way without a repetitive code.

Above implementation returns Array of CoreDataType when we fetche our records with predicate. What if we used custom datamodel in our screens instead of CoreData entityType? Our ArticleDetail screen comes up with this case.

ArticleDetail’s render(articleDetail:) method requires ArticleDetailModel but CoreDataStorable protocol implementation returns ArticleDetail. We can solve this by just introducing associatedtype DataModelType to our CoreDataStorable protocol.

typealias DataModelType = ArticleDetailModel

And mention DataModelType as ArticleDetailModel in ArticleDetailScreen.

CoreDataStorable will have a new method dataModels(with….) to get custom models. This method have a closure param transform which turns our CoreDataType into our CustomDataModel type.

You can download the source here. Thanks for reading this article.

--

--