开发者

Easy and fast way to access UIView from different threads

I have an interface like this:

@interface AView : UIScrollView
{
    UIView* m_view1;
    UIView* m_view2;
 开发者_Go百科   ...
}

-(void) method1;
-(void) method2;
...
@end

I need to access views from methods of the interface. I need to create, release, re-create them and also set properties.

The problem is, some methods of the interface are running in different threads. Since these methods access same views I have issues like one thread trying to re-create a view when another thread is trying to set some properties of a view being recreated.

How should I synchronize access to views?


First of all, do you know you can ONLY call the methods of the UIView class (and it's subclasses) in the main thread? But, if you are just doing create and release job in second thread, it's OK to do it.

Threading Considerations

Manipulations to your application’s user interface must occur on the main thread. Thus, you should always call the methods of the UIView class from code running in the main thread of your application. The only time this may not be strictly necessary is when creating the view object itself; but all other manipulations should occur on the main thread.

In addition, you can use @synchronized() {object} to lock an object. But still, you can NOT call UIView's methods in second thread (in Objective-C even set property is calling method) even you've locked it.

Objective-C supports multithreading in applications. Therefore, two threads can try to modify the same object at the same time, a situation that can cause serious problems in a program. To protect sections of code from being executed by more than one thread at a time, Objective-C provides the @synchronized() directive.

The @synchronized()directive locks a section of code for use by a single thread. Other threads are blocked until the thread exits the protected code—that is, when execution continues past the last statement in the @synchronized() block.

The @synchronized() directive takes as its only argument any Objective-C object, including self.


You can use NSLock for example, but you shouldn't update your UI from other threads. The only thread from which you should update UI Is the main thread.


UIKit can only be used safely on the main thread! Do you use NSOperation? You will see the usage ofperformSelectorOnMainThread:withObject:waitUntilDone: to move operations done from other threads to the main thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜