【问题标题】:Avoiding singletonton abuse in objective C避免在目标 C 中滥用单例
【发布时间】:2015-03-04 07:12:05
【问题描述】:

我创建了一个单例:

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

【问题讨论】:

    标签: ios objective-c singleton


    【解决方案1】:

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

    + (id)sharedManager {
    
    
        static Singleton *sharedManager = nil;
        static dispatch_once_t onceToken;
    
        dispatch_once(&onceToken, ^{
    
            sharedMyManager = [[self alloc] init];
    
        });
    
        return sharedManager;
    }
    

    【讨论】:

    【解决方案2】:

    这是因为alloc 也在内部调用allocWithZone:,参见NSObject doc

    这就是为什么您的代码 instance = [[super allocWithZone:NULL] init]; 有效而 instance = [[super alloc] init]; 无效的原因。

    【讨论】:

    • 所以 alloc 在我的代码中调用了 ovveridern allocwithzone 但 [super allocWithZone:] 没有?
    • 不,接缝你不了解继承。 super 将调用您的 allocWithZone:,因为您覆盖了它。你打电话给super allocsuper alloc 打电话给你的allocWithZone:。当您致电super allocWithZones 时,它不会致电您的allocWithZone:
    猜你喜欢
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多