ios - 如何在非 UIVIewController 单例中设置委托(delegate)? (iOS)

标签 ios delegates singleton

我通常会在 viewDidLoad 中将委托(delegate)设置为 self,但因为单例类不是 UIViewController 的子类,所以我想知道在何处为任何特定协议(protocol)设置委托(delegate)。

这是我试过但没有用的方法:

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

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

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

但这看起来很愚蠢。

我想我可以在第一次使用委托(delegate)时在类之外设置委托(delegate),但随后我依赖于记住这样做,甚至知道第一次是什么时候。

最佳答案

您可以使用初始化方法来设置委托(delegate)。

例子:

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

关于ios - 如何在非 UIVIewController 单例中设置委托(delegate)? (iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26583668/

相关文章:

ios - 使用 WatchConnectivity 获取核心数据请求

ios - 使用 colorWithPatternImage 动画 UIImageView

ios - 我的单例设置是否正确?

ruby-on-rails - 如何实现单例模型

iphone - 有没有适合初学者的关于Core Graphics的好资料?

ios - 触摸按钮时如何使用 UIScrollview 滚动到页面

ios - Objective C 委托(delegate)或 C 风格的 block 回调?

swift - 使用观察者模式设置委托(delegate)时遇到问题

swift - 如果一个类没有父类(super class),我如何遵守协议(protocol)?

node.js - Node + ES6 类 : Setting up a set of cached objects