I know UIView are not thread safe so i cant add a view on a background thread, to work around this is it ok to create a UIView on a background thread then add it on the main thread?
Note: the reason im not doing this on the main thread is because my actual code is a lot more complex and therefor takes a while to create all the views and fill the values. I dont want the UI to become un-responsive when I do this so im trying to work around this.
for example..
-(void)addLabel//called on background thread
{
UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0,0,40,100)];
[label setText:@"example"]
[self.view performSelector:@selector(addSubview:) onThread:[NSThread mainThread] withObject:example waitUntilDone:YES];
}
Thanks in advance.
From UIView:
The call to
initWithFrame:is explicitly not thread safe. The call tosetText:is likely not thread-safe, falling under the "manipulations" clause. These certainly are not promised to be thread-safe.Do your work to figure out the data on a background thread. Then create your views on the main thread. If there are a huge number of views, you can try splitting up the work using several
dispatch_async()calls onto the main queue. This may let the UI remain responsive; I haven’t experimented extensively with it.You may also want to consider switching from
UIViewtoCALayerwhere possible. MostCALayerwork can be done on background threads. If you have a huge number of views, that’s probably inefficient anyway. If it’s just that it takes a long time to calculate the data for the views, that suggests you’re not properly separating Model and View information. The Model classes should calculate everything needed independently of creating the Views.