I want to create a class in objective-c with already stored data, so that for accessing the data I don't want to instantiate the class. how can I do it?
You can use a singleton or you can use a class made only of class methods and giving you access to static data.
Here is a basic singleton implementation in ObjC:
@interface MySingleton : NSObject
{
}
+ (MySingleton *)sharedSingleton;
@property(nonatomic) int prop;
-(void)method;
@end
@implementation MySingleton
@synthesize prop;
+ (MySingleton *)sharedSingleton
{
static MySingleton *sharedSingleton;
@synchronized(self)
{
if (!sharedSingleton)
sharedSingleton = [[MySingleton alloc] init];
return sharedSingleton;
}
}
-(void)method {
}
@end
and you use it like this:
int a = [MySingleton sharedSingleton].prop
[[MySingleton sharedSingleton] method];
The class method based class would be:
@interface MyGlobalClass : NSObject
+ (int)data;
@end
@implementation MySingleton
static int data = 0;
+ (int)data
{
return data;
}
+ (void)setData:(int)d
{
data = d;
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With