我正在使用AsyncSocket从我的iPhone应用程序连接到服务器。在从服务器接收数据的代理中,我发布了一个通知,告诉tableView的代理在tableView上触发一个reloadData:
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData*)data withTag:(long)tag {
[[NSNotificationCenter defaultCenter] postNotificationName:@"PEERSTATUSCHANGED" object:self];
[sock readDataToData:[AsyncSocket CRLFData] withTimeout:-1 tag:0];
}在viewController上:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(peerStatusDidChange:) name:@"PEERSTATUSCHANGED" object:nil];
}
return self;
}
- (void)peerStatusDidChange:(NSNotification *)notification {
NSLog(@"NOTIFICATION RECEIVED");
}现在,这根本不起作用。通知已提交,但未被ViewController识别。然而,当我在applicationDidFinishLaunching中做同样的事情时:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
protocol = [[XBBProtocol alloc] init];
SourceListViewController *sourceListVC = [[[SourceListViewController alloc] initWithNibName:@"SourceListViewController" bundle:nil] autorelease];
UINavigationController *navigationController = [[[UINavigationController alloc] initWithRootViewController:sourceListVC] autorelease];
[[NSNotificationCenter defaultCenter] postNotificationName:@"PEERSTATUSCHANGED" object:self];
[protocol connectToServer];
// Override point for customization after application launch
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}我在viewController中收到了通知。
有人知道为什么吗?这与AsyncSocket的委托方法在不同的线程中有什么关系吗?
提前谢谢。
发布于 2009-06-28 15:27:24
一种可能是您的initWithNibName:bundle:方法实际上并未被调用。如果您在NIB中(而不是在代码中)实例化视图控制器,那么它将调用initWithCoder:。
检查的一种快速方法是在initWithNibName:bundle:中设置断点。
发布于 2009-06-28 20:44:29
尝试将发送通知的方法放在不同的方法中,并使用"performSelectorOnMainThread“调用它。你的网络代码很可能是在后台线程中被调用的,因此当通知触发时,它会通知同一线程上的表视图……
除了主线程,你不能在任何地方进行UI调用。
https://stackoverflow.com/questions/1055060
复制相似问题