gpt4 book ai didi

ios - 避免在 Objective-C 中滥用单例

转载 作者:行者123 更新时间:2023-11-29 10:32:37 24 4
gpt4 key购买 nike

我创建了一个单例:

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
NSAssert(FALSE, @"Please use getSharedInstance class method of MotionManager to avoid singleton abuse. =)");

return nil;
}


+ (id) getSharedInstance
{
if (!instance)
{
instance = [[super allocWithZone:NULL] init];
}

return instance;
}

为什么上面的工作正常,但下面的抛出异常?

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
NSAssert(FALSE, @"Please use getSharedInstance class method of MotionManager to avoid singleton abuse. =)");

return nil;
}


+ (id) getSharedInstance
{
if (!instance)
{
instance = [[super alloc] init];
}

return instance;
}

最佳答案

这是创建单例的正确方法:

+ (id)sharedManager {


static Singleton *sharedManager = nil;
static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

sharedMyManager = [[self alloc] init];

});

return sharedManager;
}

关于ios - 避免在 Objective-C 中滥用单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28848528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com