Use Singleton In Interface Builder? - objective-c

I have a Singleton set up like this:
static Universe *instance;
+ (Universe *)instance { return instance; }
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
instance = [[Universe alloc] init];
}
}
- (id) init
{
self = [super init];
if (self != nil) {
self.showHistory = YES;
}
return self;
}
but now I realize that I'd like to instantiate it from Interface Builder. I was thinking of just cutting into the init method like so
if (instance)
return instance;
is this a bad idea? I'd prefer IB to pick up the instance already created in the +initialize method.

This can be done. There is a section about it in Cocoa Design Patterns by Buck and Yachtman.
In your case you could do something along the lines of:
static Universe *instance;
+ (Universe *)instance { return instance; }
+ (id)hiddenAlloc
{
return [super alloc];
}
+ (id)alloc
{
return [[self instance] retain];
}
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
instance = [[Universe hiddenAlloc] init];
}
}
- (id)init
{
if(instance==nil) // allow only to be called once
{
// your normal initialization here
}
return self;
}
The nib loading code will then correctly pick up the singleton via its call to [[Universe alloc] init], and you can still use instance in your code as before.
The book has more detail and recommends implementing new and allocWithZone (both simply as return [self alloc];), plus error-reporting stubs to catch copyWithZone and mutableCopyWithZone attempts for good measure.

That's going to leak. You can get away with it if you change it to:
if(instance) {
[self release];
return instance;
}
but it still smells a bit to me. I'm curious what use you have for singletons in IB; I suspect I would avoid this construct in my code.

Related

Creating a local singleton correctly Obj C. (Not a shared global Singleton)

I'm designing a class that MUST only have one instance of itself at any time. I'm trying to avoid the common pattern of a shared singleton that is globally accessible, I only want a local object that can only be allocated once but can also be set to nil. How does this look?
static BOOL isInitialized = NO;
#implementation Single
-(instancetype) init
{
if (isInitialized == NO)
{
if (self = [super init])
{
}
isInitialized = YES;
return self;
}
else
{
NSAssert(FALSE, #"Only one instance allowed");
return nil;
}
}
-(void) dealloc
{
isInitialized = NO;
}
#end
I'm not concerned about thread safety as I only plan to use class on main thread. When the object is deferrenced the overridden dealloc should ensure a new instance can be created. Anybody see any issues with this or improvements? Cheers
It's a corner case, but as written if the call to [super init] fails then isInitialized will be set to YES (Note that in this case the passed in self is deallocated before the flag is set) - this means that no instance of the class will ever be created as there is nothing to deallocate to reset your flag. Maybe you want:
if (self = [super init])
{
isInitialized = YES;
}
return self;
Otherwise, given that you are not concerned over thread safety and you want a second allocation attempt to be a failure (your use of NSAssert), your code looks fine.
Would it be better to return the existing instance instead of crashing?
#implementation Single
- (instancetype)init {
static __weak Single *weakInstance;
Single *strongInstance = weakInstance;
if (strongInstance) {
self = strongInstance;
} else {
if (self = [super init]) {
weakInstance = self;
}
}
return self;
}
You don't need to do anything special in dealloc because the system will clear the __weak reference automatically when the instance is deallocated.
#Rob
Can the strong reference be removed from your method?
- (instancetype)init
{
static __weak id weakInstance;
if (weakInstance)
{
self = weakInstance;
}
else
{
if (self = [super init])
{
weakInstance = self;
}
}
return self;
}
seems to work.

Are local static variables released on dealloc in Objective-C / ARC?

I have a factory which handles singletons as follows
#implementation MyFactory
- (AudioEngine *)theAudioEngine
{
static AudioEngine *ae = nil;
if (ae == nil) {
ae = [[AudioEngine] alloc] init];
}
return ae;
}
#end
Are such static local variables released when the MyFactory instance is dealloc'ed?
No they are not released. You could however move the variable to the heap and have a class method to release it, which is itself called from some app-level closedown method:
static AudioEngine *_ae = nil;
#implementation MyFactory
- (AudioEngine *)theAudioEngine
{
if (_ae == nil) {
_ae = [[AudioEngine] alloc] init];
}
return _ae;
}
+ (void)cleanup
{
if (_ae != nil)
{
// No need to release when in ARC mode (thanks to #AndrewMadsen)
//[_ae release];
_ae = nil;
}
}
#end
As stated by #trojanfoe the answer is no, presumably because the compiler allocates a permanent space for the static var and being also a local var, only the method itself would ever have access to it and thus the ability to dealloc it (via = nil).
Another strategy which works presuming your factory is an instance object and not a static class:
#implementation MyFactory
{
AudioEngine *_audioEngine;
}
- (AudioEngine *)audioEngineSingleton
{
if (_audioEngine == nil) {
_audioEngine = [[AudioEngine alloc] init];
}
return _audioEngine;
}
#end
When your MyFactory instance dealloc's so will the ivars.

Objective C - deallocated variable

I have this static/singelton class that has a member variable.
Everything works just fine, however, when I quit the app, and the come back, that member variable is causing the app to crash.
I tried reinitializing the member variable, but doesn't seem to do the trick.
I am including samples of my code below, has anyone seen this before?
The header (.h) file:
#interface Metrics : NSObject {
Metrics *metrics;
Distance *distance;
}
The implementation (.m) file:
#implementation Metrics
static Metrics *metrics = nil;
+ (Metrics *)sharedInstance {
#synchronized(self) {
if (metrics == nil) {
metrics = [[Metrics alloc] init];
}
}
return metrics;
}
- (id)init {
self = [super init];
if (self) {
}
return self;
}
-(void) setupDistance
{
distance = [[Distance alloc] init];
distance.test; // it dies here after I quit the app and come back
}
And where it is used, AppDelegate.m
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[[Metrics sharedInstance] setupDistance];
}
Thank you,
Tee
When you say "quit the app" you almost certainly mean "send the app to the background." This does not terminate your application. When you become active again, you're leaking distance and assigning a new one. I suspect that something in test is actually the problem.
First, don't access your ivars directly, except in init and dealloc. Use accessors. This will make most of your problems go away.
Second, don't call setupDistance in applicationDidBecomeActive. You mean to call it in applicationDidFinishLaunchingWithOptions:. But better yet, just initialize it during Metrics init. Why have this internal Metrics detail in the app delegate?
applicationDidBecomeActive will get called when it comes back from sleep calling to setup in the distance again. It's wierd that you're calling a property (.test) and not assigning. Is test doing work? Should it be a method? What's it doing?
Also, in a singleton you have to overload quite a few things. Here's a good template for a singleton that I use.
static MySingleton *sharedInstance = nil;
#implementation MySingleton
#pragma mark -
#pragma mark class instance methods
#pragma mark -
#pragma mark Singleton methods
+ (MySingleton*)sharedInstance
{
#synchronized(self)
{
if (sharedInstance == nil)
sharedInstance = [[MySingleton alloc] init];
}
return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
#synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [super allocWithZone:zone];
return sharedInstance;  // assignment and return on first allocation
}
}
return nil; // on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX;  // denotes an object that cannot be released
}
- (void)release {
//do nothing
}
- (id)autorelease {
return self;
}
#end

Singleton not initializing correctly

I have the following code that I am calling using this statement: SQLiteDB *db = [[[SQLiteDB alloc] init] autorelease];
The problem is "sharedSQLiteDB" is not being called, but rather "allocWithZone" is, and therefore "checkIfDatabaseExists" is not being called, which is where the database is created.
I don't understand why... (i.e. what am I doing wrong?)
#import "SQLiteDB.h"
static SQLiteDB *sharedSQLiteDB = nil; // makes this a singleton class
#implementation SQLiteDB
#synthesize searchPaths, documentPath, databasePath, cDatabasePath;
#pragma mark Singleton Methods
+ (SQLiteDB *) sharedSQLiteDB {
if(!sharedSQLiteDB) {
sharedSQLiteDB = [[SQLiteDB alloc] init];
[sharedSQLiteDB checkIfDatabaseExists]; // check to see if d/b exists
}
return sharedSQLiteDB;
}
+(id)allocWithZone:(NSZone *)zone { // makes sure another instance is not allocated
if(!sharedSQLiteDB) {
sharedSQLiteDB = [super allocWithZone:zone];
return sharedSQLiteDB;
}
else {
return nil;
}
}
-(id)copyWithZone:(NSZone *)zone {
return self;
}
-(void) release {
// no-op
}
In the singleton pattern your use pattern should be:
SQLiteDB* db = [SQLiteDB sharedSQLiteDB];
They way you are calling it doesn't fit the singelton pattern. All access should be through your sharedSQLiteDB message.
In other words you shouldn't be initializing via typical Cocoa patterns (SQLiteDB *db = [[[SQLiteDB alloc] init] autorelease]; is incorrect and full of problems) outside the scope of the class.
In a singleton using the default initialization pattern for the language (alloc/init for ObjC or the default constructor for C++) should generate a compile time error message since the constructor/init method should be protected.
See the Wikipedia entry. consult the Design Pattern C++ bible. There is even a version for Cocoa
Good luck.
It isn't executing your + (SQLiteDB *) sharedSQLiteDB method because you're not actually calling that method anywhere.
As you've seen, when you call [[SQLiteDB alloc] init], the allocWithZone method is called.
Change your call to be SQLiteDB *db = [SQLiteDB sharedSQLiteDB], which will call your checkIfDatabaseExists method in this case. However, if [[SQLiteDB alloc] init] is called somewhere else, then the checkIfDatabaseExists method call will still be skipped.
Maybe consider moving the checkIfDatabaseExists method into an init method so that it will be called for both your singleton method and your allocWithZone.
Honestly I don't see any error...
However I post the code I used to create a Singleton. It's from a source that now I don't remember the link... it's not my code.
static DataManager *_instance;
#implementation DataManager
+ (DataManager*)sharedInstance
{
#synchronized(self) {
if (_instance == nil) {
_instance = [[super allocWithZone:NULL] init];
// Allocate/initialize any member variables of the singleton class her
// example
//_instance.member = #"";
}
}
return _instance;
}
#pragma mark Singleton Methods
+ (id)allocWithZone:(NSZone *)zone
{
return [[self sharedInstance]retain];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return NSUIntegerMax; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
I hope it helps
I highly recommend using the SyntesizeSingleton header file first created by Matt Gallagher.
Find the latest version (that I know about) here:
https://github.com/cjhanson/Objective-C-Optimized-Singleton
It makes creating a singleton dead simple.
Here's an example header:
#import <Foundation/Foundation.h>
#interface Example : NSObject {}
+(Example*)sharedExample;
#end
And the corresponding .m:
#import "FMUser.h"
#import "SynthesizeSingleton.h"
#implementation Example
SYNTHESIZE_SINGLETON_FOR_CLASS(Example);
#end
[Example sharedExample] is created for you. It's pretty sweet.

Is this valid code to create a NIB-instantiated singleton?

Assume that I instantiate an object of class MyGreatClass in my NIB (as usual by simply dragging an "Object" to the NIB and settings its class to MyGreatClass).
I want access to that instance anywhere in my codebase, without introducing coupling, i.e. without passing objects around like crazy, and without having an outlet to it in, say, [NSApp delegate]. (The latter would make AppDelegate terribly bulky with time.)
I ask: Is the following considered a good code to accomplish this?
//imports
static MyGreatClass *theInstance = nil;
#implementation MyGreatClass
+ (MyGreatClass *)sharedInstance
{
NSAssert(theInstance != nil, #"instance should have been loaded from NIB");
return theInstance;
}
- (id)init //waking up from NIB will call this
{
if (!theInstance)
theInstance = self;
return theInstance;
}
// ...
If this work as expected, I would after the app is loaded be able to access my instance via sharedInstance.
What do you think?
UPDATE: Hmm, on the second thought, the above init method maybe overkill. This is way simpler to think about:
- (id)init
{
NSAssert(!theInstance, #"instance shouldn't exist yet because only "
#"the NIB-awaking process should call this method");
theInstance = self;
return theInstance;
}
Again, what do you think?
The proper way to create a singleton is to override allocWithZone: to ensure another object cannot be created. Overriding init allows the new object to be created, but not initialized. It is thrown away because the init method simply ignores it and returns the object that has been created already. Here is how I would do it:
+ (MyGreatClass *)sharedInstance {
NSAssert(theInstance != nil, #"instance should have been created from NIB");
return theInstance;
}
+ (MyGreatClass *)allocWithZone:(NSZone *)zone {
if(theInstance) return theInstance;
return [[self alloc] init];
}
- (id)init {
if(theInstance) return theInstance;
if(self = [super init]) {
theInstance = self;
// other initialization
}
return self;
}
- (void)release {}
- (void)dealloc {
return;
[super dealloc]; // Prevent compiler from issuing warning for not calling super
}
I overrode release and dealloc to ensure that the singleton would not be deallocated. If you don't do this, you should retain and autorelease it in the sharedInstance method. If you want to support multithreading, you should also synchronize access to the theInstance variable.