angelokh
angelokh

Reputation: 9428

singleton in objective c

I saw a singleton example on objective-c book. However, I don't know if there is difference of meaning of 'singleton' definition between objective-c and other langs. Can this [[SingletonClass alloc] init] still be used to create a new object? If yes, how to guarantee there is only one object in the memory?

#import "SingletonClass.h"

@implementation SingletonClass

static SingletonClass *sharedInstance = nil;

// Get the shared instance and create it if necessary.
+ (SingletonClass*)sharedInstance {
    if (sharedInstance == nil) {
        sharedInstance = [[super allocWithZone:NULL] init];
    }

    return sharedInstance;
}

// We can still have a regular init method, that will get called the first time the             Singleton is used.
- (id)init
{
    self = [super init];

    if (self) {
        // Work your initialising magic here as you normally would
    }

    return self;
}

Upvotes: 3

Views: 5835

Answers (5)

Charlie Fish
Charlie Fish

Reputation: 20526

You can create a singleton in Objective-C by doing the following:

+(MyAPI *)shared {
    static dispatch_once_t queue;
    static MyAPI *singleton = nil;
 
    dispatch_once(&queue, ^{
        singleton = [[MyAPI alloc] init];
    });

    return singleton;
}

This will also ensure that it is thread safe. Without using the dispatch_once you run the risk of multiple threads trying to access it at the same time when one is in the middle of allocating it, and the other is trying to use it.

Upvotes: 0

Sumayya Ansari
Sumayya Ansari

Reputation: 79

Singleton class is used to save the data for use anywhere in app.

//SingletonObject
#define saveDataSingletonObject ((SaveDataSingleton*)[SaveDataSingleton sharedManager])

@interface SaveDataSingleton : NSObject

@property (nonatomic,strong) NSMutableArray *DataArr;
+ (id)sharedManager;
-(void)clearAllSaveData;

@end

@implementation SaveDataSingleton
@synthesize DataArr;
+ (id)sharedManager {
    static SaveDataSingleton *sharedManager;
    if(!sharedManager) {
        @synchronized(sharedManager) {
            sharedManager = [SaveDataSingleton new];
        }
    }
    return sharedManager;
}
-(void)clearAllSaveData{
    DataArr=nil;
}
- (id)init {
    if (self = [super init]) {
        DataArr = [[NSMutableArray alloc]init];
    }
    return self;
}
// using setter getter save and retrieve data
+(void)setDataArr:(NSMutableArray *)Dataarr
{
    self.DataArr = [[NSMutableArray alloc]initWithArray:Dataarr];
}

+(NSMutableArray *)DataArr
{
    return self.DataArr;
}
@end

Save and Retrieve data // Use singleton Object

// save data using setter function.
[saveDataSingletonObject setDataArr:Array];
//fetch data using getter function.
NSArray *arr=[saveDataSingletonObject DataArr];

Upvotes: -1

justin
justin

Reputation: 104698

I don't know if there is difference of meaning of 'singleton' definition between objective-c and other langs.

It follows the common definition of languages derived from C.

Can this [[SingletonClass alloc] init] still be used to create a new object?

Yes

If yes, how to guarantee there is only one object in the memory?

Avoid enforcing the pattern (e.g. do not force it to be a singleton). Just make a normal object. Then if you really want only one instance, create an instance and save it someplace for reuse (your app delegate is one typical place for this, because it is typically created once per execution).

In practice, most (>95%) ObjC singleton implementations i've seen in the wild are used for the wrong reasons, and would have been better or as good as normal objects.

Every solution linked in the answers so far has (at minimum) subtle problems, dangers, or undesirable side-effects.

Upvotes: 2

Caleb
Caleb

Reputation: 124997

If you want a true singleton, i.e. an object that can be instantiated only once, take a look at Apple's documentation: Creating a Singleton Instance.

Basically, the idea is to override a number of methods related to allocating and managing objects: +allocWithZone (which is called by +alloc), -retain, -release, -copyWithZone, etc., so that it becomes quite difficult to create more than one instance of your singleton class. (It's still possible to create a second instance by calling the runtime directly, but this should be enough to get the point across.)

Pretty much every blogger who has ever written about Objective-C in any capacity has offered an opinion on how to implement singletons. Many of those opinions seem pretty good, and most of them are fairly similar. It's clear that Dave DeLong knows what he's talking about, and his piece on singletons is short, sweet, and gets straight to the point.

Upvotes: 3

EricS
EricS

Reputation: 9768

There is no language support for singletons, but you can do it by hand. Look at the singleton example here. It doesn't look like it is thread-safe, though. I would allocate the object in +initialize instead of +sharedManager.

Upvotes: 0

Related Questions