0

我正在使用 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];
}

在视图控制器上:

- (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 的委托方法在不同的线程中有关吗?

提前致谢。

4

2 回答 2

1

一种可能性是您的initWithNibName:bundle:方法实际上没有被调用。如果您在 NIB 中(而不是在代码中)实例化视图控制器,则它会initWithCoder:改为调用。

一种快速检查的方法是在initWithNibName:bundle:.

于 2009-06-28T15:27:24.087 回答
1

尝试将发送通知的方法放在不同的方法中,并使用“performSelectorOnMainThread”调用它。您的网络代码很可能在后台线程中被调用,因此当通知触发时,它会通知同一线程上的表格视图......

除了主线程之外,您不能对任何东西进行 UI 调用。

于 2009-06-28T20:44:28.937 回答