How to Manage Persistent Objects in iOS Apps
Interposing a class that mediates between the in-memory object and the database is an approach for making the responsibility of managing persistent objects easier for iOS apps. This pattern is known as Data Mapper. The Figure below shows the interaction between classes in a simple version of the Data Mapper.
Basically, all persistent operations that access the database (that is, create, retrieve, update and delete) are the responsibility of the Data Mapper. The application simply makes the appropriate requests of the Data Mapper.
The Data Mapper pattern is an abstraction with which you can handle persistent objects when their lifecycle management is complex. In fact, with Data Mapper, the objects in memory don’t even need to know that there’s a database present; they don’t need SQL or any knowledge of the database schema.
Implementing a good Data Mapper is complicated. For example, the methods in Active Record suggest that a single invocation (such as a finder method) results in one SQL query. This isn’t always true. Loading an object with multiple contained objects, for instance, could require loading the line items as well. If the objects are complex, a find request could load an entire graph of objects.
Mappers may need to handle classes that turn into multiple fields in multiple tables, classes with inheritance, and relating objects once they’re fetched from the data store. The data-store mapping layer needs to understand which objects have changed, which new ones have been created, and which have been destroyed.
If multiple updates are made to the persistent records of a set of objects, then all these manipulations would have to take place inside a transaction. The Data Mapper pattern often lets Active Record handle single objects, while Data Mapper takes care of complicated requirements, such as inheritance, deep retrieval and linking together of objects, queries based on complex relationships, transactions encompassing a working set of objects, and so on.
Data Mapper acts like a true object manager while delegating object-level operations to Active Record. This makes for a better OO design overall because Mapper cohesively handles the manager responsibility, while Active Record handles the simple persistence of the object (also cohesively). Also, the management policy is separated from the persistence mechanism. Therefore, the management policy and the persistence mechanisms are loosely coupled.
Finally, the Data Mapper pattern (with some variations) has become a core part of iOS with the provision of the Core Data component in iOS.