singleton in objective c

不羁的心 提交于 2020-01-30 06:45:30

问题


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;
}

回答1:


Colin Wheeler has a post on Singletons in Cocoa.

I agree with Colin about the undesirability of Singletons.




回答2:


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.




回答3:


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.




回答4:


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.




回答5:


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];


来源:https://stackoverflow.com/questions/7143162/singleton-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!