An implementation of Repository and Unit Of Work pattern in Objective-C. This project provide you a template to implement DAO layer in iOS project, including concurrency update database.
- Create Model classes
Start creating your model class using Core Data designer or just create POCO class. Inherit your model classes from BaseModel class or BaseManagedObjectModel class included in project, BaseMode is pure POCO class, BaseManageObjectModel class is class inherited from NSManagedObject class incase you used Core Data designer to generate model classes. See BaseModel and BaseManagedObjectModel class for reference.
- Create Repository classes
Drag Repositories and Liraries folder to your project.
+ Generic folder:
This folder contains all Repository interfaces.- RPIRepository: generic repository interface, it describe abstract methods for a repository, all your custom repository interface must inherite from this interface. You just don't have to modify anything in this interface, just let it be there.
- RPIDbUnitOfWork: this is unit of work interface, it describes all repository properties like this:
@protocol RPIDbUnitOfWork
@required
// User repository for User model
@property(nonatomic,strong,readonly) id userRepository;
// Photo repository for Photo model
@property(nonatomic,strong,readonly) RPIPhotoRepository photoRepository;
....
@end
You need to describe repository property to return an instance of repository class.
+ Implements folder:
This folder contains all Repository implementations.
- RPCoreDataUnitOfWork: an implementation of RPIDbUnitOfWork interface, you can return an repository instance with your model class without creating new implementation files by define:
Or if you had to create custom repository implementation, just create new one and return its instance like this:- (id) xxxRepository{
return [[RPGenericRepository alloc] initWithDbContext:dbContext withModel:[YOUR_MODEL_CLASS class]];
}
See RPWeatherRepository and RPCityRepository class for example. Simply replace or remove these repositories with your own repositories.- (id) cityRepository{
return [[RPCityRepository alloc] initWithDbContext:dbContext withModel:[City class]];
}
- Usage through UnitOfWork
1. Get unit of work single instance
id unitOfWork = [UnitOfWork sharedInstance];2. Get a repository
id repository = [unitOfWork userRepository];3. Make changes
User *user = [repository create]; user.name = @"User 1";4. Save changes
[unitOfWork saveChanges];