Pretty much all the apps I write now are backed by CoreData in some way or another. It is the best way of setting up and managing objects that are persisted, this allows the app to show data to the user when they are offline or in bad reception areas.

Why the post?

Initially I thought, well it’s Apple’s ‘modern’ language it will integrate seamlessly with CoreData. After setting up CoreData and creating objects I realised some tinkering would need to be done, hence the reason for this post.

First off I instantly talked to the one developer who I knew who did Swift, he answered the phone and said ‘It’s the CoreData problem right?’ and then continued to explain to me a few things that needed to be done before CoreData could work.

Issue number one

Inside the UI for XCDataModel Apple prefix the class of your Entity with the name of the project i.e. projectName.class which breaks the creating and fetching by entity name. You will need to delete this and make sure the class is either one you want or the same name as your entity is called. I believe this also happens in Objective-C, so it’s either a move towards some better process but half baked or a bug within CoreData framework itself.

Issue number two

Once you have generated your NSManagedObject Subclass of your entity you will need to put @objc({name_of_your_class}) below the imports. Unfortunately this needs to be done every time the subclass is re-generated from the datamodel.

Conclusion

However now that you have done these two bits CoreData is actually much nicer in Swift, I follow the pattern of having an extension per object subclass so it knows how to create and fetch itself, and with private in Swift it really allows a level of control over which methods you choose to expose.

So there we are, a couple of really niggly parts to an otherwise great system, I know it took someone a long time going through Apple’s documentation to find these snippets, however it wasn’t me and it now isn’t you.

All Posts
×

Almost done…

We just sent you an email. Please click the link in the email to confirm your subscription!

OKSubscriptions powered by Strikingly