ios - 从类方法中获取对 sharedInstance 的访问

标签 ios objective-c singleton class-method

我正在将项目转换为 SDK。我需要将几个实例方法转换为类方法。我收到有关使用“self”的编译器警告。警告是“使用 Class 表达式初始化 Store* 的不兼容指针类型。此 Store 类是单例 sharedInstance。

我的类 Store 中有这样的方法:

+ (void) dispatchStoreSource {

__weak Store *ref = self;  <--- issue is here

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSError *error = nil;
    NSArray *things = [ref fetchThings:&error];

    //dispatch back to main queue
    if (![ref updateSource:source forUser:user error:&error]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            result(nil, error);
        });
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            result(source, nil);
        });
    }
  });


}

解决这个问题的正确方法是什么?我应该这样做吗?

 __weak Store *ref = [Store sharedInstance];

最佳答案

您的ref 是指向Store 类对象的指针。但是你的类方法中的 self 并不指向你的类的分配对象(=你的单例),它是你的类,IOW Store (不是对象,而是类) .如果你已经实现了 sharedInstance 类方法,就像这样......

+ (instancetype)sharedInstance {
  static Story *instance;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    instance = [[self alloc] init];
  });
  return instance;
}

...就这样做ref = [self sharedInstance];

关于ios - 从类方法中获取对 sharedInstance 的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22457158/

相关文章:

ios - 如何创建一个能够同时显示文本和表情符号的 UITextField?

ios - 弹出 UIViewController 后,MKMapView autorelease 不调用 dealloc

ios - 在 iOS 7 中始终获得唯一的设备 ID

java - 如何在 Java 中创建一个不可变的单例?

android - 移动设备上的 StageVideo

iOS 9 : Warning "All interface orientations must be supported unless the app requires full screen" for universal app

ios - 最新比赛数据游戏中心

ios - 将 Objective-C 代码转换为 Swift : okay to omit release calls?

java - 获取同一 Java 应用程序的实例(如果该应用程序已在运行)

java - 为什么直接访问无法获取单例实例?