gpt4 book ai didi

iphone - 从不同线程访问 UIView 的简单快捷方式

转载 作者:行者123 更新时间:2023-12-01 17:27:50 25 4
gpt4 key购买 nike

我有一个这样的界面:

@interface AView : UIScrollView
{
UIView* m_view1;
UIView* m_view2;
...
}

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

我需要从接口(interface)的方法访问 View 。我需要创建、发布、重新创建它们并设置属性。

问题是,接口(interface)的某些方法在不同的线程中运行。由于这些方法访问相同的 View ,因此当另一个线程尝试设置正在重新创建的 View 的某些属性时,我遇到了一个线程尝试重新创建 View 的问题。

我应该如何同步对 View 的访问?

最佳答案

首先,你知道你只能在主线程中调用 UIView 类(及其子类)的方法吗?但是,如果你只是在做 创建 发布在第二个线程中工作,可以这样做。

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.



此外,您可以使用 @synchronized() {object}锁定一个对象。但是,即使您已将其锁定,您也不能在第二个线程中调用 UIView 的方法(在 Objective-C 中,即使设置属性也是调用方法)。

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.

关于iphone - 从不同线程访问 UIView 的简单快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7316570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com