Skip to content

Instantly share code, notes, and snippets.

@dodikk
Created December 30, 2016 12:14
Show Gist options
  • Select an option

  • Save dodikk/62fbcc8b6923bb5ba527833a50b93a8d to your computer and use it in GitHub Desktop.

Select an option

Save dodikk/62fbcc8b6923bb5ba527833a50b93a8d to your computer and use it in GitHub Desktop.
Realm Wrapper Example
  1. "Realm builder" block is injected to a wrapper class
  2. GCD queue is injected to a wrapper class
  3. Realm is not accessed directly outside a wrapper class. It's only constructed there.
  4. 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment