As I get to some performance issues in my app and find that I use database access in a bad way.
So I decided to move to singleton pattern.
I need someone to review this code and confirm me that I made a good database access via singleton pattern or I am doing something wrong:
This is the class:
@interface DataAccessController : NSObject{
sqlite3 *databaseHandle;
}
+ (id)sharedManager;
-(void)initDatabase;
...
+ (id)sharedManager {
static DataAccessController *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
- (id)init {
if (self = [super init]) {
[self initDatabase]; // open database connection
}
return self;
}
...
AppDelegate.m
DataAccessController *d = [DataAccessController sharedManager];
Usage through the application every time I need data I use:
DataAccessController *d = [DataAccessController sharedManager];
NSMutableArray* data = [d getAllRecordedUnits];
sharedMyManager
tonil
explicitly, but I would as a general practice when creating variables. \$\endgroup\$ – JRG-Developer Dec 10 '13 at 23:29dispatch_once
with a simple if statement. I think that sincedispatch_once
became the singleton idiom it is often misused in two ways: 1. unnecessarily, in singletons that are intended to be single threaded only and 2. as magic DWIM dust, in multithreaded singletons in whichdispatch_once
is the author's first and last attempt at synchronization. \$\endgroup\$ – Rhythmic Fistman Dec 11 '13 at 1:55