這裏是我想要的:objective-c/iphone:如何設置某個對象的所有方法都會在特定的線程上運行?
在自己的線程中創建一個'生命'的對象,所有的方法都應該在該線程中執行。
即:
// i'm in the main thread
MyClass *myObject = [ [MyClass alloc] init ]; // it creates its own thread
[myObject method1]; // should execute the method1 in myObject's thread
[myObject method2]; // should execute the method2 in myObject's thread
[myobject release]; // should deallocate everything that is used for myObject and remove myObject's thread
我一直在閱讀有關線程和runloops。我在init
方法中創建了一個新線程,其入口點是runloop方法。 runloopMethod只是設置運行NSRunLoop所需的最基本的東西並運行它。
aThread = [[NSThread alloc] initWithTarget:self selector:@selector(runloopMethod) object:nil];
[aThread start];
它工作得很好,但是當我調用一個方法(即:[myObject method1];
)從主線程運行時,它在主線程上,我怎麼知道呢?,好,因爲方法1執行多個操作,阻止UI。我所要做的就是將呼叫重定向這樣:
// on MyClass.m
-(void) method1 {
if ([NSThread currentThread] != aThread) {
[self performSelector:@selector(method1) onThread:aThread withObject:nil waitUntilDone:YES];
}else {
// do my stuff
}
它的工作,但這種方式限制了我,我也有一些對你的問題:
我已經意識到,如果我在X線程和調用某個對象的方法,它將在X線程中執行。我認爲這個方法調用會被添加到X線程的runloop中(不知道它是否是這個詞)。對?
有沒有辦法來設置:任何對我的對象的方法的調用將在對象的線程上執行? (沒有做所有這些東西)。
另外,這是我正在做什麼的正確方法? method1,method2等是我的函數的同步版本..所以他們會阻止用戶界面。那'爲什麼我假設有另一個線程的方式。
感謝您的閱讀!
btw。我沒有使用GCD,因爲我需要支持iOS 3
'runloopMethod'在哪裏定義?我想做同樣的事情,但是我對這部分感到困惑 – abbood 2012-09-12 06:59:19