Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在一个objective-c单例中混淆_Objective C_Singleton - Fatal编程技术网

在一个objective-c单例中混淆

在一个objective-c单例中混淆,objective-c,singleton,Objective C,Singleton,我一直在读关于objective-c单例的例子。 .m代码看起来像 +(MySingleton*)sharedMySingleton{ @synchronized([MySingleton class]) {if (!_sharedMySingleton) if(!_sharedMySingleton) return _shareMySingleton; } .... -(id)init{ self = [super init]; if(self != nil)

我一直在读关于objective-c单例的例子。 .m代码看起来像

+(MySingleton*)sharedMySingleton{
@synchronized([MySingleton class])
{if (!_sharedMySingleton)
    if(!_sharedMySingleton)
    return _shareMySingleton;
}

....
-(id)init{
    self = [super init];
    if(self != nil){}
    return self;
}
....
谢谢你的例子,但我有一个困惑的地方,在你的代码中,我想知道
静态MySingleton*\u sharedMySingleton
是在哪个地方初始化的。例如,如果我们需要一些实现,比如

-(id)init{
    self = [super init];
    if(self != nil){
        _sharedMySingleton = self
    }
    return self;
}

您错误地从发布的链接中复制了部分代码

@implementation MySingleton
static MySingleton* _sharedMySingleton = nil;

+(MySingleton*)sharedMySingleton
{
    @synchronized([MySingleton class])
    {
        if (!_sharedMySingleton)
            [[self alloc] init];

        return _sharedMySingleton;
    }

    return nil;
}

+(id)alloc
{
    @synchronized([MySingleton class])
    {
        NSAssert(_sharedMySingleton == nil, @"Attempted to allocate a second instance of a singleton.");
        _sharedMySingleton = [super alloc];
        return _sharedMySingleton;
    }

    return nil;
}

-(id)init {
    self = [super init];
    if (self != nil) {
        // initialize stuff here
    }

    return self;
}

-(void)sayHello {
    NSLog(@"Hello World!");
}
@end
看看你所问的帖子中的代码实际上是有道理的。 他在静态方法
+(MySingleton*)sharedMySingleton
中所做的是检查
\u sharedMySingleton
对象是否有一个值,如果没有,则返回该值并初始化。 alloc方法是设置singleton对象的方法,它不在初始值设定项中设置。从技术上讲,它是相同的,因为它将是同一个对象上的一个点,稍后将被初始化。 我希望这能澄清您的困惑。

您可以使用宏,因为它很容易使用

在实现文件中(m)

和头文件

+ (ClassName *) sharedInstance;
+ (ClassName *) sharedInstance;