Reputation: 16783
I want to create a special class for holding a lot of values like strName, strNo, intPassword...So that several other classes can modify the same value in this class. I want to use the dot syntax to call its properties like
Values.strName = ...;
I don't want to initialize the class everytime before I read/write its values because some of its values are still in use.
I call the class 'Values' and design it using the following code:
@interface Values : NSObject {
IBOutlet NSString *strName;
}
@property (nonatomic, copy) NSString *strName;
@end
I import "Values.h" to another class and call the property using
Values.strName = @"Name";
I don't create an object of 'Values' to avoid the data be overwritten. An error pops up saying that 'syntax error before . token'. Any other ways to create a class storing global variables but needn't be initialized when using these data?
Upvotes: 1
Views: 625
Reputation: 17170
Another solution to thos problem is to add the variables (or classes) to the AppDelegate object. It's easy for the AppDelegate to become a ball-of-fluff but if these variables really are propertiers of your app, it's the right place for them to go.
You can always get a reference to your AppDelegate using [UIApplication sharedApplication].delegate
(you may need to cast this)
Upvotes: 4
Reputation: 96333
I want to create a special class for holding a lot of values like strName, strNo, intPassword...
Why? There's nothing wrong with putting immutable and primitive objects in read-only global variables:
NSString *const strName = @"Name";
const NSInteger intPassword = 0xDEADBEEF;
If you want to prefix them as being globals, “g” (as in gStrName
, etc.) is common and works fine.
You may be tempted to say “but globals are evil!”, but think about what you're saying: Why are globals evil?
const
) variables.)As long as none of these complaints applies, there is nothing wrong with global variables. They are quite common in Cocoa (most of its string constants, for example, are actually global variables).
Upvotes: 3
Reputation: 1414
If you use a singleton pattern, then you can achieve something close to this. Using the 'SynthesizeSingleton.h' helper by Matt Gallagher:
// Values.h
#import "SynthesizeSingleton.h"
@interface Values : NSObject {
...
}
// props
+ (Values *)sharedValues;
@end
// Values.m
@implementation Values
SYNTHESIZE_SINGLETON(Values);
@synthesize props;
@end
Then to use your singleton:
NSString *myVal = [[Values sharedValues] someValue];
or:
Values *v = [Values sharedValues];
NSString *myVal = v.someValue;
Upvotes: 2