If you are having multiple views in your application, and in that case you want to have a variable accessible to every view, you should always create a Model/Data class and define the variable in it. Something like this :
Objective-C :
//DataClass.h
@interface DataClass : NSObject {
NSString *str;
}
@property(nonatomic,retain)NSString *str;
+(DataClass*)getInstance;
@end
//DataClass.m
@implementation DataClass
@synthesize str;
static DataClass *instance = nil;
+(DataClass *)getInstance
{
@synchronized(self)
{
if(instance==nil)
{
instance= [DataClass new];
}
}
return instance;
}
Now in your view controller you need to call this method as :
DataClass *obj=[DataClass getInstance];
obj.str= @"I am Global variable";
This variable will be accessible to every view controller. You just have to create an instance of Data class.
Swift :
class DataClass {
private var str: String!
class var sharedManager: DataClass {
struct Static {
static let instance = DataClass()
}
return Static.instance
}
}
Usage : DataClass.sharedManager.str
Using dispatch_once
class DataClass {
private var str: String!
class var sharedInstance: DataClass {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: DataClass? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = DataClass()
}
return Static.instance!
}
}
Usage : DataClass.sharedManager.str