NSOperation:完成任务后更新UI

时间:2012-08-30 10:52:53

标签: objective-c cocoa nsoperationqueue performselector

我用NSOperation和NSOperationQueue构建了一个测试项目。 只有一个文本框:@property (weak) IBOutlet NSTextField *textbox;

在后台执行此操作:

- (void)main
{
    NSURL *url = [NSURL URLWithString:@"http://google.com"];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {
        NSString *response = [request responseString];
        NSLog(@"MainThread: %@", ([NSThread isMainThread] ? @"YES" : @"NO"));
        [[AppDelegate sharedManager] performSelectorOnMainThread:@selector(pageLoaded:)
                                           withObject:response
                                        waitUntilDone:NO];
}

在主线程上调用的选择器:

- (void)pageLoaded:(NSString*)document
{
    [textbox setStringValue:document]; // does nothing
    NSLog(@"Textbox: %@", textbox); // returns nil
}

为什么文本框返回nil?

1 个答案:

答案 0 :(得分:0)

嗯,我有两个想法:

  1. 逼真一:[AppDelegate sharedManager]返回不同 您打开applicationDidFinishLaunching的对象。 如果将AppDelegate添加到XIB +上就可以了 单独的单例实例。
  2. 一个神秘主义者一个:只有一个 AppDelegate,但属性值无效。如果是这样的话 在这种情况下,解决问题的最简单方法是 将“弱”改为“分配”(以确定它是否正在释放 问题),而不是重新定义 setTextbox 来查找谁调用它。
  3. 但我敢打赌它是#1。