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.
Related
I have a singleton class which is allocation object only one time in whole project. Few code line is below..
declaration...
....
MyClassName *classObject = nil
In the init method, the code is like below..
-(id) init(){
self = [super init];
if(classObject == nil){
1. Allocate object code here
2. classObject = self;
3. return classObject
} else {
return classObject;
}
}
But my problem is that how will I dealloc this object. I am calling this init method from all the class and it is returning classObject reference every time.
My approach....
From the dealloc method in appdelegate.m, I am calling a function (releaseObject)which is defined in MyClassName . Here is the definition of function body...
-(void) releaseObject {
[self release]; // Confusion: Will it dealloc classObject reference?
[super release];
}
Is this good idea dealloc this object? My problem is that I don't have to dealloc object until application is not being closed.
The answer is don't bother ever to release the singleton. It is supposed to last the lifetime of the application anyway and will go away automatically along with everything else when the process terminates. You may find that the dealloc method on your app delegate never gets called for the same reason.
If you have clean up to do on application close, it's probably better to move that into a separate method and just call that when the application is about to terminate.
a simpler pattern for a singleton IMO is to have a class method to return the singleton instance and not mess about with releasing stuff in init.
+(MyClass*) sharedInstance
{
static MyClass* theInstance = nil;
static dispatch_once_t pred;
dispatch_once(&pred, ^{ theInstance = [[MyClass alloc] init]});
return theInstance;
}
The above uses dispatch_once to ensure the initialising block only happens once in the lifetime of the application. You can still create other instances by calling init directly but that is advantageous IMO.
I'd recommend to make an extra class method in your singleton:
static MyClassName *classObject = nil;
...
+ (MyClassName *)sharedInstance {
...
}
+ (void)releaseSharedInstance {
[classObject release];
classObject = nil;
}
If your class is a singleton, in AppDelegete dealloc just call
[[YourClass instance] release];
Here is workaround via Objective C++:
class StaticOwner {
private:
id<NSObject> object;
public:
StaticOwner(id<NSObject> obj) { object = [obj retain]; }
~StaticOwner() { [object release]; }
id<NSObject> instance() {return object;}
};
Usage example:
+ (MySingleton*) sharedInstance {
static StaticOwner owner = StaticOwner([[[MySingleton alloc] init] autorelease]);
return owner.instance();
}
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
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.
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 want to write some methods in a class so that other classes can call these methods using [instance methodName:Parameter].
If the class is a subclass of UIViewController, I can use initWithNibName to initialize it. But I want to write the methods in an NSObject's subclass, how can I initialize it?
iphony is correct, but he or she doesn't say that you need to write the init method yourself. Your init method should generally look something like this:
- (id) init
{
if (self = [super init])
{
myMember1 = 0; // do your own initialisation here
myMember2 = 0;
}
return self;
}
Although the apple documentation says
The init method defined in the NSObject class does no initialization; it simply returns self.
and one can just be tempted to write
- (id) init
{
myMember1 = 0; // do your own initialisation here
myMember2 = 0;
return self;
}
this is WRONG and not following what is explicitly stated in documentation:
In a custom implementation of this (init) method, you must invoke super’s
designated initializer then initialize and return the new object.
MUST. Not should, could, ought to, etc.
You should not assume NSObject's init does not change in future; nor the superclass from which your custom class derives.
I find this may work:
TheClass *newObject = [[TheClass alloc] init];
//do something here
[newObject release];