0

我试图在目标 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 类的所有对象的前一个对象的地址。这是单例的正确实现吗?谢谢

4

2 回答 2

4

您应该使用“singleton”或“ dispatch_oncesharedInstance static int”等类方法而不是alloc-init。有关更详细的解释,我建议您执行“单身人士:您做错了”。该帖子中的代码

+(MyClass *)singleton {
    static dispatch_once_t pred;
    static MyClass *shared = nil;

    dispatch_once(&pred, ^{
        shared = [[MyClass alloc] init];
    });
    return shared;
}
于 2013-04-19T10:06:14.237 回答
0

Objective-C 中的单例是这样实现的:

+(id)sharedInstance {
    static id instance = NULL;
    if (instance == NULL) instance = [[YourClassName alloc] init];
    return instance;
}

如果有可能从多个线程调用它,请改用 David 的解决方案。

于 2013-04-19T10:09:09.187 回答