1

Possible Duplicate:
Where to store global constants in an iOS application?

I'd like to store config variables in a central place. The variables do not change on runtime. They should be accessible from any class in the project.

My current approach is to have a GlobalSettings.h file with the config variables defined like this

#define kCacheAge 10.0 //Max. Cache Age in Seconds
#define kNavigationTitleTint colorWithRed:0.443 green:0.471 blue:0.502 alpha:1.0
#define kNavigationTitleFont boldSystemFontOfSize:20.0

... and include their name wherever I need it.

Downsides:

  • I need to include this GlobalSettings.h file in every Class manually
  • I cannot insert these constants as a part of Strings (the string handling seems to be stronger than the replacement action)

Is there a better way to do this, maybe avoiding the mentioned downsides? Any best-practices for storing config variables?

Community
  • 1
  • 1
Bernd
  • 11,133
  • 11
  • 65
  • 98
  • Avoid using comments in `#define`s. If you use something like `if (kCacheAge == 1.0) {` it'll break the line by inserting the comment in the middle of the line. – Cyrille Jan 05 '13 at 13:54
  • Yes, if you want to document your #define constants in comments then place the comment in the line above. – Hermann Klecker Jan 05 '13 at 14:02
  • I kinda disagree that this is an exact duplicate. (Not to mention that the question @Cyrille proposes as the original is kind of unfortunately misleading in its own right, since it uses compile time headers when the user seems to be asking for an equivalent for localized string resource loading, which is boilerplate stuff, but not mentioned in the accepted answer.) – ipmcc Jan 05 '13 at 15:32

2 Answers2

5

If you include your GlobalSetting.h header in the projects Prefix Header, it will automatically be included in every file in your project. Look for a file in your project called something like <YourProjectName>-Prefix.pch. The standard one for an iOS project looks like this:

//
// Prefix header for all source files of the 'IOSTest' target in the 'IOSTest' project
//

#import <Availability.h>

#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
#endif

You would add #import "GlobalSettings.h" below the Foundation import in this case.

Nicolas Bachschmidt
  • 6,475
  • 2
  • 26
  • 36
ipmcc
  • 29,581
  • 5
  • 84
  • 147
-2

One option are INI files as they do not require a recompilation once the values change.

A simple (untested from my end) example can be found in this thread.

Community
  • 1
  • 1
Philip Allgaier
  • 3,505
  • 2
  • 26
  • 53