我正在将一个项目转换为SDK。我需要将几个实例方法转换为类方法。我得到一个关于使用"自我"的编译器警告。警告是"使用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
在你的类方法不指向你的类的分配对象(=你的单例),这是你的类,低Store
(不是对象,而是类)。如果你已经实现了sharedInstance
类方法,像这样…
+ (instancetype)sharedInstance {
static Story *instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
…ref = [self sharedInstance];
是的,你应该使用__weak Store *ref = [Store sharedInstance];
否则,让我们使用原始的Store静态引用。
的例子:
static Store = _store = nil;
__weak Store * ref = _store;