我试图在目标C中实现单例设计模式。 这是我的代码
在.h文件中
#import <Foundation/Foundation.h>
@interface BSCustomClass : NSObject
{
NSString *string;
}
@property (nonatomic,strong)NSString *string;
@end
在.m文件中
#import "BSCustomClass.h"
@implementation BSCustomClass
static int i;
static BSCustomClass* object;
@synthesize string;
-(id)init
{
if(i==0)
{
object=[super init];
i=1;
object.string=@"tunvir Rahman";
}
return object;
}
@end
现在,如果我想使用alloc和init从main创建BSCustomClass的对象,那么它将调用自己的init方法并检查静态变量i。如果i = 0,则假设到目前为止没有创建对象并创建一个对象,之后它将返回BSCustomClass类的所有对象的前一个对象的地址。 这是单身人士的正确实施吗? 谢谢
答案 0 :(得分:4)
您应该使用dispatch_once
而不是static int
和类方法,例如“singleton”或“sharedInstance”而不是alloc-init。有关更详细的说明,请参阅“Singletons: You're doing them wrong”。该帖子的代码
+(MyClass *)singleton {
static dispatch_once_t pred;
static MyClass *shared = nil;
dispatch_once(&pred, ^{
shared = [[MyClass alloc] init];
});
return shared;
}
答案 1 :(得分:0)
Objective-C中的单身人士实现如下:
+(id)sharedInstance {
static id instance = NULL;
if (instance == NULL) instance = [[YourClassName alloc] init];
return instance;
}
如果有可能从多个线程调用它,请改用David的解决方案。