UI不会使用performSelectoronMainThread构建

时间:2011-03-07 10:35:33

标签: iphone multithreading cocoa

我在下载时使用performSelectorInBackground并解析一些xml。解析xml后,我调用performSelectorOnMainThread来根据xml中的值构建我的UI。构建UI函数确实被调用,但没有任何东西被放到屏幕上。如果不是,那么从后台线程调用主线程应该是o.k吗?

如果我不在后台线程上执行xml解析,则UI添加就好了。

-(id) myCustomInit:(Data *) data;

{
    if ( self= [super init]) {
            baseURL=data.url;
    [self performSelectorInBackground:@selector(getXML) withObject:nil];

    }


    return self;

}


-(void) getXML
{
    // Set up a pool for the background task.

    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    // XML parsing code removed for brevity



    [self performSelectorOnMainThread:@selector(handleUIOnXMLComplete) withObject:nil waitUntilDone:YES];

    [pool release];


}

-(void)handleUIOnXMLComplete
{

// add buttons etc to view

    UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];

[self.view addSubview:button];

}

修改

这是父UIViewController中的代码,实际上是添加了视图

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    NewViewData *rld=nil;

    rld=[dataArray objectAtIndex:indexPath.row];
    NewView *controller = [[NewView alloc] myCustomInit:rld ];


    controller.title = rld.Title;
    controller.view.backgroundColor = [UIColor blackColor];

    [table.navigationController pushViewController:controller animated:YES];
    //[table.tableView reloadData];

}

1 个答案:

答案 0 :(得分:0)

允许从后台线程触发对主线程上的方法的调用,并且很好。

setNeedsLayout和setNeedsDisplay不需要调用 - 当您向视图添加子视图时,无论如何都会触发新添加项目的显示。

如果用以下内容替换整个handleUIOnXMLComplete方法会怎样?

-(void)handleUIOnXMLComplete
{

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    label.text = @"XXXXXXX YYYYYYYY";
    label.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:label];
}

我尽可能快地再现了你的情况,上面的代码确实有效 - 我看到了“XXXXXXX YYYYYYYY”标签。

顺便说一句,我不会设置全新的self.view - 最好修改现有的self.view。

顺便说一下,在您发布的代码中,您没有在自定义UIButton上设置框架!在创建按钮之后以及将其添加到视图之前,请执行button.frame = CGRectMake(0.0, 0.0, 160.0, 160.0);之类的操作。

相关问题