This is kind of newbie question on objective-c:
I would like to create a static class available throughout my entire code to be accessed by any object. This class will act as a container of several objects.
Can anybody provide a short example of code as how to declare static global variables and methods ?
For my Globals class I have something like this
The .h file looks like this
#interface Globals : NSObject
{
}
+ (Globals *)instance;
#end
and the .m file is like this
import "Globals.h"
#implementation Globals
- (id)init
{
self = [super init];
if (self)
{
}
return self;
}
+ (Globals *)instance
{
static Globals *instance = nil;
#synchronized(self)
{
if (instance == nil)
{
instance = [[Globals alloc] init];
}
}
return instance;
}
- (void)dealloc
{
[super dealloc];
}
#end
of course this is a very basic example of a Globals class
you should think of it making as Singleton class,
Find below the some link that will help you to understand Singleton pattern in Objective-C.
A note on Objective-C singletons,
Singleton Classes.,
Using the Singleton Pattern in Objective-C,
And you could also use the Factory pattern for creating objects ..
Create a class and have your app delegate hold an instance of the class -- if you really need that global visibility. Global mutable state such as global variables and singletons are bad smells. A superior solution can be thought up.
Related
I need to create an object for example NSString and let other classes get/set the value for it.
thx. for help :)
The easiest way to do this is to attach the value as a property to a singleton instance of some class. One singleton instance that already exists in your application is the application delegate. So, just add an NSString property to your application delegate and you can access it from any class in your app (as long as you #import your application delegate).
In your application delegate:
#property(nonatomic, strong) NSString* someString;
In your other classes:
[self doSomethingWithAString:((YourAppDelegateClass*)[[UIApplication sharedApplication] delegate]).someString];
Create a Singleton/Shared class.
#implementation SINGLETON
static SINGLETON *instance = nil;
+(SINGLETON*)sharedInstance{
#synchronized(self) {
if (instance == nil) {
instance = [[SINGLETON alloc] init];
}
return instance;
}
}
EDIT:
This will come handy... Objective-C Singleton problem. Object recognized in one class but not another
I want to save the "dataFilePath" as a static variable so that it can be initialized when first time use "Constants" and no need to instantiate the Class , for example [Constants SDataFilePath]. But the trues is that the init method is not called. How can I do to meet my request? (In Java the construct method will be called the fist time to access the Class).
#implementation Constants
static NSString *dataFilePath;
-(id)init
{
NSLog(#"init!");
if(self = [super init]) {
dataFilePath = [self getDataFilePathWithArg:dbfile];
}
return self;
}
+(NSString *)SDataFilePath {
return dataFilePath;
}
....
#end
Well you could make Constants a singleton. Leave your code how it is and add this method to the .m:
+ (Constants *)sharedConstants
{
static Constants *_sharedConstants = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedConstants = [[self alloc] init];
});
return _sharedConstants;
}
And the method declaration to the .h:
+ (Constants *)sharedConstants;
Then access your variable like this:
[[Constants sharedConstants] SDataFilePath]
That will force an init the first time you access [Constants sharedConstants] (and only the first time). Also, you'll need to change +(NSString *)SDataFilePath to an instance method, not class method:
-(NSString *)SDataFilePath
This cannot be done this way. Any reason why you want this path to be static? You might want to look into setting dataFilePath with a getter, but no setter and instantiating the class as a singleton. That way you can set the path by some internal method and share the instance as a singleton. See here
I have a class, in that class I have set up a singleton patter and have a method, here is a short example of what it looks like.
#pragma mark Singleton Methods
+ (id)sharedManager {
#synchronized(self) {
if (sharedMyManager == nil)
sharedMyManager = [[self alloc] init];
}
return sharedMyManager;
}
- (id)init {
if (self = [super init]) {
//so some init stuff here
//...
}
-(void)savemethod {
//etc etc
}
I'm wondering if I am to call/initalize the singleton class to be used like so
//set up plist controller class as a singleton so that you dont loose cache numbers etc
EnginePropertiesController *enginePC = [EnginePropertiesController sharedManager];
then later on in the same class where I have initialized the singleton I call the save method...
[enginePC saveMethod];
So what im wondering is saveMethod part of the same instance? I think it is because i am using the same initialization name enginePC.. but would like some clarification on this.
If I'm understanding you, you are correct that saveMethod would be called on the singleton instance. What you name a pointer has no bearing on what it points to.
Greetings,
I'm trying to write my first iPhone app. I have the need to be able to access data in all views. The data is stored when the user logs in and needs to be available to all views thereafter.
I'd like to create a static class, however I when I try to access the static class, my application crashes with no output on the console.
Is the only way to write data to file? Or is there another cleaner solution that I haven't thought of?
Many thanks in advance,
Use a singleton class, I use them all the time for global data manager classes that need to be accessible from anywhere inside the application. You can create a simple one like this:
#interface NewsArchiveManager : NetworkDataManager
{
}
+ (NewsArchiveManager *) sharedInstance;
#end
#implementation NewsArchiveManager
- (id) init
{
self = [super init];
if ( self )
{
// custom initialization goes here
}
return self;
}
+ (NewsArchiveManager *) sharedInstance
{
static NewsArchiveManager *g_instance = nil;
if ( g_instance == nil )
{
g_instance = [[self alloc] init];
}
return g_instance;
}
- (void) dealloc
{
[super dealloc];
}
#end
I don't know what you mean with "static class", but what you want is a singleton. See this question for various methods on how to set one up.
I have create a SinglestonClass in my code but i have a problem.
My variable are initialized in the -init method but when i call the singlestonClass these variable are re-initialize.
Can you help me for create a single initialization for my variable?
thanks.
#implementation SingletonController
#synthesize arrayPosition;
#synthesize arrayMovement;
#synthesize actualPosition;
#synthesize actualMove;
#synthesize stopThread;
+(SingletonController*)sharedSingletonController{
static SingletonController *sharedSingletonController;
#synchronized(self) {
if(!sharedSingletonController){
sharedSingletonController = [[SingletonController alloc]init];
}
}
return sharedSingletonController;
}
//I don't want a re-initialization for these variables
-(id)init{
self = [super init];
if (self != nil) {
arrayPosition = [[NSMutableArray alloc]init];
arrayMovement = [[NSMutableArray alloc]init];
actualPosition = [[Position alloc]init];
actualMove = [[Movement alloc]init];
stopThread = FALSE;
}
return self;
}
-(void) dealloc {
[super dealloc];
}
#end
Your init method should not be called by anyone except for your singleton class itself. That's what the sharedSingletonController method is for. This is your factory method that is responsible for returning the same static instance of your class. I'd also suggest that you rename the static instance of your singleton object and/or the sharedSingletonController selector itself to disambiguate between the two and for cleaner design. In this particular case, it may confuse someone who has to read your code.
Without seeing how the client code is calling on your singleton factory method, it's difficult to decipher where your problem is. We'd need to see the rest of the code including how it's being called. In your client code, you should be using something such as:
SingletonController *sigController = [SingletonController sharedSingletonController];
DO NOT DO:
SingletonController *sigController = [[SingletonController alloc] init];
Read here for more information in the Cocoa Fundamentals Guide.