UI Won't build using performSelectoronMainThread
I'm using performSelectorInBackground in download and parse some xml. Once the xml is parsed I call performSelectorOnMainThread to build my UI based on values in the xml. The build UI function does get called but nothing gets put onto the screen. It should be o.k to call the main thread from a background thread should it not?
If I don't perform the xml parsing on a background thread the UI add just fine.
-(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:UIButt开发者_开发知识库onTypeRoundedRect];
[self.view addSubview:button];
}
Edit
This is the code in the parent UIViewController Thats actually adds the view
- (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];
}
Triggering a call to a method on the main thread, from a background thread, is allowed and fine.
setNeedsLayout and setNeedsDisplay shouldn't need calling -- when you add a subView to a view, the display of the newly added item is triggered anyway.
What happens if you replace your entire handleUIOnXMLComplete method with the following?
-(void)handleUIOnXMLComplete
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
label.text = @"XXXXXXX YYYYYYYY";
label.backgroundColor = [UIColor yellowColor];
[self.view addSubview:label];
}
I did a quick reproduction, as far as I could, of your situation and the above code does work -- I get to see the "XXXXXXX YYYYYYYY" label.
I'd avoid setting a whole new self.view
by the way -- it's preferable to modify the existing self.view.
By the way, in the code you posted, you're not setting a frame on your custom UIButton! So do something like button.frame = CGRectMake(0.0, 0.0, 160.0, 160.0);
after you make your button and before you add it to the view.
精彩评论