Reputation: 3274
In a simple project I want to set a constant that I will use throughout.
For example, an NSDictionary
with keys being month names and values being days in that month.
How can this be done? (i.e. What is the syntax and where to put it?) If this example is already possible using built-in functions, just pretend it isn't for the purposes of this question.
Upvotes: 8
Views: 8725
Reputation: 21426
The accepted answer is correct, but if you prefer operate with variable (not trough method). I can suggest this pattern:
@implementation MyClass
static NSSet *mySetOfObjects;
+ (void)initialize {
mySetOfObjects = [[NSSet alloc] initWithObjects:@"one", @"two", @"three", nil];
}
// Example usage:
+ (BOOL)isRecognizedString:(NSString *)searchItem {
return [mySetOfObjects containsObject:searchItem];
}
@end
As for me - it looks better.
For more details the source is here.
Upvotes: 3
Reputation: 2512
Let's assume you want to declare an NSString constant in your class that holds a url. In your header .h file you will need the following:
#import
extern NSString * const BaseURL;
@interface ClassName : NSObject {
You will then need to set it's value in your main .m file as follows:
#import "ClassName.h"
NSString * const BaseURL = @"http://some.url.com/path/";
@implementation ClassName
You can now access this constant throughout your class or subclasses. Here's an example of usage:
NSString *urlString = [NSString stringWithFormat:@"%@%@", BaseURL, @"filename.html"];
Upvotes: 2
Reputation: 726509
The answer depends on the type of your constant. If all you need is an int
or a double
, you can use preprocessor and the #define CONST 123
syntax. For Objective C classes, however, you need to do a lot more work.
Specifically, you would need to hide the constant behind a class method or a free-standing function. You will also need to add a prototype of that method or function in the header file, provide a function-scoped static variable to store the constant, and add code to initialize it.
Here is an example using a simple NSDictionary
:
Header: MyConstants.h
@interface MyConstants
+(NSDictionary*)getConstDictionary;
@end
Implementation: MyConstants.m
+(NSDictionary*)getConstDictionary {
static NSDictionary *inst = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
inst = @{
@"key1": @"value1",
@"key2": @"value2",
@"key3": @"value3"
};
});
return inst;
}
Usage:
NSString *val = [[MyConstants getConstDictionary] objectForKey:@"key2"];
Upvotes: 19
Reputation: 122391
If your constants are strings then you can use this form:
MyObject.h:
extern NSString *const kJanuary;
....
extern NSString *const kDecember;
@interface MyObject : NSObject
{
...
}
@end
MyObject.m:
NSString *const kJanuary = @"January";
....
NSString *const kDecember = @"December";
@implementation MyObject
....
@end
You can then use the constant kJanuary
, for example, from anywhere when using your class.
Upvotes: 0