Where to store global constants in an iOS application?

后端 未结 11 1683
孤城傲影
孤城傲影 2020-11-28 18:01

Most of the models in my iOS app query a web server. I would like to have a configuration file storing the base URL of the server. It will look something like this:

11条回答
  •  余生分开走
    2020-11-28 18:29

    Global declarations are interesting but, for me, what changed deeply my way to code was to have global instances of classes. It took me a couple of day's to really understand how to work with it so I quickly summarized it here

    I use global instances of classes (1 or 2 per project, if needed), to regroup core data access, or some trades logics.

    For instance if you want to have a central object handling all restaurant tables you create you object at startup and that is it. This object can handle database accesses OR handle it in memory if you don't need to save it. It's centralized, you show only useful interfaces ... !

    It's a great help, object oriented and a good way to get all you stuff at the same place

    A few lines of code :

    @interface RestaurantManager : NSObject
        +(id) sharedInstance;
        -(void)registerForTable:(NSNumber *)tableId;
    @end 
    

    and object implementation :

    @implementation RestaurantManager
    
    + (id) sharedInstance {
        static dispatch_once_t onceQueue;
    
        dispatch_once(&onceQueue, ^{
            sharedInstance = [[self alloc] init];
            NSLog(@"*** Shared instance initialisation ***");
        });
        return sharedInstance;
    }
    
    -(void)registerForTable:(NSNumber *)tableId {
    }
    @end
    

    for using it it's really simple :

    [[RestaurantManager sharedInstance] registerForTable:[NsNumber numberWithInt:10]]

提交回复
热议问题