我正在将项目转换为 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/