views:

759

answers:

2

For my brand new ORM (chibi-ORM) I face a desing decision.

I'm building the API for relationships, like:

@interface SamplePerson : DbObject {
    NSString *name;
        DbObjectRelation *cities;
}

Now, for DbObjectRelation I have this mockup:

@interface DbObjectRelation : NSObject {
    NSMutableArray *childRows;
    DbObject *parent;
    BOOL isLoaded;
}

-(void) load;

-(void) addObject:(DbObject *) childRow;
-(void) removeObject:(DbObject *) childRow;

- (id)initWitParent:(DbObject *)parentObject;

So, I need a way inside load of know which database use for load the records.

I think in have in my DB connection something like:

static NSString *currentDbNameSingleton = nil;

+(NSString *)currentDbName {
    @synchronize( self ) {
        if ( currentDbNameSingleton == nil ) {
            currentDbNameSingleton = [[NSString alloc]
        }
    }
    return sharedInst;  
}

+(void) setCurrentDbName(NSString *)name {
    @synchronize( self ) {
      currentDbNameSingleton = [name copy];
    }
}

But wonder if is better build the DB class as a singleton. This is for iPhone projects...

+2  A: 

Using a set of class accessors/mutators around a static variable like you're currently doing is pretty reasonable. Another pretty common solution if you're not going to change the database name would be to put it in a separate file, say Constants.h, along with other constant strings like dictionary and user defaults keys.

If you have additional code related to your database that you can refactor into a single place, then that's a pretty good point to built a singleton class for your database stuff. I wouldn't create a class just to hold a string though.

Marc Charbonneau
+1  A: 

For strings that don't change you should create them as constants.

i.e. In your database connection file:

const NSString *CurrentDbName = @"name of database";

Note the capitlization to convey compile-time generation and constant-ness.

It's slightly more efficient than a singleton for a string. Of course, you can't do this with other types of Objective-C object because they can't be created by the compiler. For these, use a singleton.

If other parts of your program need access to the string, you should use an extern reference in your database's header file:

extern const NSString *CurrentDbName;
Matt Gallagher
I'd do this slightly differently: extern NSString * const CurrentDbName in the header file. and NSString * const CurrentDbName = @"name of database" in teh implementation. The position of const makes the pointer itself a constant.
Abizern