views:

81

answers:

3

Hi everyone,

I would like to add some constant keys for my application, these constant can be accessed anywhere in program. So I declare constant 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 it in 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 show error in MinIntervalViewController class:

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

Do I miss something? Any help would be appreciated.

Thanks

+1  A: 

In the .h file:

extern NSString * const MIN_INTERVAL_KEY;

In one (!) .m file:

NSString * const MIN_INTERVAL_KEY = @"MIN_INTERVAL_KEY";

And what you seemed to have missed is to actually import the header file declaring MIN_INTERVAL_KEY ;-) So if you declared it in SmokingViewController.h but like to use it in MinIntervalViewController.m, then you need to import "SmokingViewController.h" in your MinIntervalViewController.m. Since Objective-C is really more or less an extension to C all C visibility rules apply.

Also, what helps to debug things like that is to right-click on the .m file in Xcode and select "Preprocess". Then you see the file preprocess, i.e. after CPP has done its work. This is what the C compiler REALLY is digesting.

DarkDust
+4  A: 

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];
Philip Regan
Every line starting with an @ or } in your code can be removed, IMHO :-) There really is no need to define a class here.
DarkDust
This could be true, but leaving the class syntax in keeps the file consistent with every other header/implementation pair in an application. To each their own.
Philip Regan
A: 

use

#define NSString *MIN_INTERVAL_KEY @"MIN_INTERVAL_KEY";

or use static variable in the Constants class.

karim