单例中的委托将不起作用
我有一个从外部数据库(PTDatabaseAccsesser)下载数据的单例。 下载完所有数据后,单例应该调用 UITableViewController 子类的委托。但是,我收到此错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:
'-[__NSCFType doneDownloadingData]: unrecognized selector sent to instance...
这就是我将委托设置为 UITableViewController 的子类的方式:
- (void)viewDidLoad {
[[PTDatabaseAccesser sharedInstance] setDelegate:self];
NSLog(@"%@", [[PTDatabaseAccesser sharedInstance] delegate]);
}
NSLog 显示这里的一切都是正确的。
这是 PTDatabaseAccsesser 中调用委托的代码:
NSLog(@"%@", [self delegate]);
[[self delegate] doneDownloadingData];
但是,此处的 NSLog 显示委托的类型与上面的错误消息中的类型相同。
这就是我创建单例的方式:
static PTDatabaseAccesser *sharedInstance;
+ (PTDatabaseAccesser *)sharedInstance {
@synchronized(self) {
if (!sharedInstance) sharedInstance = [[PTDatabaseAccesser alloc] init];
}
return sharedInstance;
}
+ (id)alloc {
@synchronized(self) {
sharedInstance = [super alloc];
}
return sharedInstance;
}
我通过在上面的两个方法实现中使用断点来确保单例可以工作。
I have a singleton that downloads data from an exterior database (PTDatabaseAccsesser).
When all data has been downloaded the singleton should call on a delegate which is a subclass of UITableViewController. However, i get this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:
'-[__NSCFType doneDownloadingData]: unrecognized selector sent to instance...
This is how I set the delegate to the subclass of UITableViewController:
- (void)viewDidLoad {
[[PTDatabaseAccesser sharedInstance] setDelegate:self];
NSLog(@"%@", [[PTDatabaseAccesser sharedInstance] delegate]);
}
The NSLog shows that everything is correct here.
This is the code from the PTDatabaseAccsesser that calls on the delegate:
NSLog(@"%@", [self delegate]);
[[self delegate] doneDownloadingData];
The NSLog here however is showing that the delegate is of the same type as in the error message above.
This is how I create the singleton:
static PTDatabaseAccesser *sharedInstance;
+ (PTDatabaseAccesser *)sharedInstance {
@synchronized(self) {
if (!sharedInstance) sharedInstance = [[PTDatabaseAccesser alloc] init];
}
return sharedInstance;
}
+ (id)alloc {
@synchronized(self) {
sharedInstance = [super alloc];
}
return sharedInstance;
}
I have made sure that the singleton works by using breakpoints in the two method implementations above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
+alloc 中的代码似乎不必要,并且可能是错误的根源。据我所知,
sharedInstance
在+alloc
中获取其初始值,这意味着-sharedInstance
中的if条件可能永远不会被执行并且您正在对未初始化的对象调用方法。请尝试使用此代码,这也恰好更高效。The code in the +alloc seems unnecessary and is probably the source of the error. From what I can see,
sharedInstance
gets its initial value in+alloc
, which means that your if-condition in-sharedInstance
is probably never executed and you are calling a method on an uninitialized object. Try this code instead, which also happens to be more efficient.