Where to store global constants in an iOS application?

后端 未结 11 1651
孤城傲影
孤城傲影 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

    Well, you want the declaration local to the interfaces it relates to -- the app-wide constants file is not a good thing.

    As well, it's preferable to simply declare an extern NSString* const symbol, rather than use a #define:


    SomeFile.h

    extern NSString* const MONAppsBaseUrl;
    

    SomeFile.m

    #import "SomeFile.h"
    
    #ifdef DEBUG
    NSString* const MONAppsBaseUrl = @"http://192.168.0.123/";
    #else
    NSString* const MONAppsBaseUrl = @"http://website.com/";
    #endif
    

    Apart from the omission of the C++ compatible Extern declaration, this is what you will generally see used in Apple's Obj-C frameworks.

    If the constant needs to be visible to just one file or function, then static NSString* const baseUrl in your *.m is good.

提交回复
热议问题