【问题标题】:How to set delegate in non-UIVIewController singleton? (iOS)如何在非 UIVIewController 单例中设置委托? (iOS)
【发布时间】:2014-10-27 08:37:03
【问题描述】:

我通常会在viewDidLoad 中将委托设置为self,但由于单例类不是UIViewController 的子类,我想知道在哪里为任何特定协议设置委托。

以下是我尝试过但不起作用的方法:

+ (instancetype)sharedInstance {

    static id sharedInstance;
    static dispatch_once_t once;
    dispatch_once(&once, ^{

        sharedInstance = [[[self class] alloc] init];

    });

    static dispatch_once_t once2;
    dispatch_once(&once2, ^{

        SharedManager.sharedInstance.delegate = SharedManager.sharedInstance;

    });

    return sharedInstance;
}

由于上述方法不起作用,唯一接近的方法是为每个类方法设置委托,如下所示:

+ (void)classMethod1 {

    SharedManager.sharedInstance.delegate = SharedManager.sharedInstance;

    //class method 1 code here
}

+ (void)classMethod2 {

    SharedManager.sharedInstance.delegate = SharedManager.sharedInstance;

    //class method 2 code here, etc...
}

但这似乎很愚蠢。

我想我可以在第一次使用委托时将其设置在班级之外,但我依赖于记住这样做,甚至知道第一次是什么时候。

【问题讨论】:

    标签: ios delegates singleton


    【解决方案1】:

    您可以使用 init-method 来设置委托。

    例子:

    static Singleton *sharedInstance = nil;
    
    + (Singleton *)sharedInstance {    
        static dispatch_once_t pred;        // Lock
        dispatch_once(&pred, ^{             // This code is called at most once per app
            sharedInstance = [[Singleton alloc] init];
        });
    
        return sharedInstance;
    }
    
    - (id) init {
        self = [super init];
        if (self) {
            self.delegate = self;
            //more inits
            //...
        }
        return self;
    }
    

    【讨论】:

    • 确实,添加一个 init 实例方法确实有效!我最初反对它是因为它是以静态方式调用的。我不确定它为什么有效,但它确实有效。
    • 是的,这很令人困惑,但是尽管该方法是静态的,但它会创建一个对象。这也意味着您可以添加非静态方法并调用它们,即 - (void) logMe { NSLog(@"logMe"); } 并用 [[Singleton sharedInstance] logMe]; 调用它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多