haisergeant haisergeant - 2 months ago 22
Objective-C Question

Constant in objective-c

I would like to add some constant keys for my application, these constants can be accessed anywhere in program. So I declare the constants in interface file:

#import <UIKit/UIKit.h>
NSString * MIN_INTERVAL_KEY = @"MIN_INTERVAL_KEY";
NSString * MAX_TOBACCO_KEY = @"MAX_TOBACCO_KEY";
NSString * ICON_BADGE = @"ICON_BADGE";

@interface SmokingViewController : UIViewController {
}


And I would like to access them from the MinIntervalViewController class:

- (void)viewDidAppear:(BOOL)animated {
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
if (user) {
self.selectedValue = [user objectForKey:MIN_INTERVAL_KEY];
}
[super viewDidAppear:animated];
}


But the application shows an error in the MinIntervalViewController class:

error: 'MIN_INTERVAL_KEY' undeclared (first use in this function)

Do I miss something? Any help would be appreciated.

Thanks

Answer

Constants.h

#import <Cocoa/Cocoa.h>

@interface Constants : NSObject {   

}

extern int const kExampleConstInt;
extern NSString * const kExampleConstString;

@end

Constants.m

#import "Constants.h"


@implementation Constants

int const kExampleConstInt = 1;
NSString * const kExampleConstString = @"String Value";

@end

To use:

#import "Constants.h"

Then, simply call the specific variable you wish to use.

NSString *newString = [NSString stringWithString:kExampleConstString];
Comments