Search code examples
objective-ccocoa-touchdesign-patternscore-datadto

Correct way of dealing with Core Data NSManagedObjects in an iOS application


When I have worked with Java applications involving a database and ORM (object relationship manager) the architecture was usually separated so when working with database entities in the database layer you worked directly with the entities. But if you needed to access the entities in the GUI you would create a data transfer object (DTO) of the entity and then use it in the GUI layer.

What is the preferred approach in iOS applications?

One example would be that I do a fetch from Core Data to retrieve some objects in a ViewController and then display the results in a TableView in the ViewController. Is it necessary to convert the NSManagedObjects to DTOs before showing the results?


Solution

  • What is the preferred approach in iOS applications? Is it necessary to convert the NSManagedObjects to DTOs before showing the results?

    No, it is not neccessary. The managed object is already a (generic) object wrapping the database entity. You can access the managed object's properties (ie the entitys attributes) using -valueForKey: calls. But the preferred approach is to subclass NSManagedObject to fit your entities. In Xcode there is an option to generate subclasses automatically (editor-> generate NSManagedObject subclass). That way you get your own subclass object for your entities and can access their properties using dot notation. On fetching objects, just let the result be of type of that subclass.

    If you want to add custom methods to your entity objects, you should create a category on your managed object subclass. This is because if you change your db scheme and have to let xcode recreate your subclasses, it completely overwrites the and your custom methods would be lost.