- "Realm builder" block is injected to a wrapper class
- GCD queue is injected to a wrapper class
- Realm is not accessed directly outside a wrapper class. It's only constructed there.
- Each query returns unmanaged POD objects.
POD == "Plain Old Data"
| @interface HPLabRepositoryRealm : NSObject <HPLabModelRepository> | |
| - (instancetype)init NS_UNAVAILABLE; | |
| + (instancetype) new NS_UNAVAILABLE; | |
| - (instancetype)initWithRealm:(RLMRealmBuilderBlock)realmBuilder | |
| operationQueue:(dispatch_queue_t)queue | |
| NS_REQUIRES_SUPER | |
| NS_DESIGNATED_INITIALIZER | |
| __attribute__((nonnull)); | |
| @end | |
| #import "HPLabRepositoryRealm.h" | |
| // entity | |
| #import "HPLabRecordRealm.h" | |
| @interface HPLabRepositoryRealm () | |
| @property (nonatomic) RLMRealmBuilderBlock realmBuilder; | |
| @property (nonatomic) dispatch_queue_t queue; | |
| @end | |
| @implementation HPLabRepositoryRealm | |
| - (void)loadLabRecordsAsync:(OnLabResultsListLoadedBlock)callback | |
| { | |
| NSParameterAssert(nil != callback); | |
| __weak HPLabRepositoryRealm* weakSelf = self; | |
| RLMRealmBuilderBlock realmBuilder = self.realmBuilder; | |
| GCDActionBlock task = ^void() { | |
| HPLabRepositoryRealm* strongSelf = weakSelf; | |
| RLMRealm* realm = realmBuilder(); | |
| NSArray<HPLabRecordPOD*>* unmanagedLabs = [strongSelf loadLabRecordsListInRealm:realm]; | |
| callback(unmanagedLabs, nil); | |
| }; | |
| dispatch_async(self.queue, task); | |
| } | |
| - (NSArray<HPLabRecordPOD*>*)loadLabRecordsListInRealm:(RLMRealm*)realm | |
| { | |
| RLMResults* sortedDataset = [self sortedDatasetForLabRecordsListInRealm:realm]; | |
| NSArray* result = [self getUnmanagedRecordListForDataset:sortedDataset]; | |
| return result; | |
| } | |
| - (NSArray<HPLabRecordPOD*>*)getUnmanagedRecordListForDataset:(RLMResults*)dataset | |
| { | |
| NSMutableArray* result = [NSMutableArray new]; | |
| for (HPLabRecordRealm* managedLabRecord in dataset) | |
| { | |
| HPLabRecordPOD* unmanagedLabrecord = [[HPLabRecordPOD alloc] initWithLabRecord:managedLabRecord]; | |
| [result addObject:unmanagedLabrecord]; | |
| } | |
| NSArray* immutableResult = [NSArray arrayWithArray:result]; | |
| return immutableResult; | |
| } | |
| @end | |