Constant in objective-c

I would like to add some constant keys for my application, these constants can be obtained anywhere in the program. Therefore, I declare constants in the 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" is undeclared (first used in this function)

Did I miss something? Any help would be appreciated.

thanks

+6
objective-c iphone cocoa-touch constants
source share
2 answers

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 

For use:

 #import "Constants.h" 

Then just call the special variable you want to use.

 NSString *newString = [NSString stringWithString:kExampleConstString]; 
+18
source share

In the .h file:

 extern NSString * const MIN_INTERVAL_KEY; 

In one file (!). M:

 NSString * const MIN_INTERVAL_KEY = @"MIN_INTERVAL_KEY"; 

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

In addition, what helps to debug such things is to right-click on the .m file in Xcode and select β€œPreprocess”. Then you will see the file preprocess, that is, after CPP has completed its work. This is what the C compiler REALLY digests.

+2
source share

All Articles