I want to declare a static int variable in one class and have access to it in every other class. What is the best way to do this?
Here are some ways you could try
Declaring the global variables in appdelegate
Creating a singleton class and putting the global variables there.
appdelegate is also a kind of singleton class
Function definition:
-(NSString*)ReadAppDelegateInstanceVariable:(NSString*)InstVar
{
AppDelegate *appDel=(AppDelegate *)[UIApplication sharedApplication].delegate;
return [appDel valueForKey:InstVar];
}
Function Calling:
[self ReadAppDelegateInstanceVariable:@"someInstanceVariableName"];
Only one instance of class can exist.
Sample singleton declaration:
@interface SigletonClass : NSObject
{
//declare instance variable
}
+ (id)sharedSingletonClass;
@end
Sample singleton implementation:
Approach 1: Using GCD
@implementation SigletonClass
+ (id)sharedSingletonClass {
static SigletonClass *sharedClass = nil;
static dispatch_once_t onceToken;//The way we ensure that it’s only created once is by using the dispatch_once method from Grand Central Dispatch (GCD).
dispatch_once(&onceToken, ^{
sharedClass = [[self alloc] init];
});
return sharedClass;
}
- (id)init {
if (self = [super init]) {
//init instance variable
}
return self;
}
@end
Approach 2: Without using GCD
@implementation SigletonClass
+ (id)sharedSingletonClass {
static SigletonClass *sharedClass = nil;
@synchronized(self) {//To safeguard threading issues
if (sharedClass == nil)
sharedClass = [[self alloc] init];
}
return sharedClass;
}
- (id)init {
if (self = [super init]) {
//init instance variable
}
return self;
}
@end
Function definition:
-(NSString*)ReadSingleTonInstanceVariable:(NSString*)InstVar
{
SigletonClass sObj=[SigletonClass sharedSingletonClass];
return [sObj valueForKey:InstVar];
}
Function Calling:
[self ReadSingleTonInstanceVariable:@"SomeInstanceVariableName"];
NSString to int:
-(int)ConvertToIntFromString:(NSString*)str
{
return str.intValue;
}
As far as I’m aware, there are no performance issues with doing it one way over another.
I always prefer singleton class rather than appdelegate because the code will be clutter free and I consider overusing appdelegate as smelly code.