2011-03-09 112 views
0

我正在接近線程可可提供的新方法。 特別是,我創建一個新的線程使用可可觸摸 - 線程和動畫

[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil]; 

方法。

一切都很好,直到現在,但我遇到了一個奇怪的行爲,也許你可以澄清我的事情。 例如,我的線程是:

-(void)myMethod{ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    UIImage *img=[UIImage imageNamed:@"animage.png"]; 
    UIImageView *imgV=[[UIImageView alloc]init]; 
    [self.view addSubview:imgV]; 
    [imgV setFrame:CGRectMake(100, 100, 200, 200)]; 
    [imgV setImage:img]; 
    [NSThread sleepForTimeInterval:10.5]; 
    [imgV release]; 
    [pool release]; 
} 

我不明白爲什麼sleepForTimeInterval命令後,顯示我的形象。 有什麼想法?

謝謝。

+0

我還沒有意識到這一點。完成。 – Lorenzo 2011-03-09 18:05:39

回答

1

任何與UI相關的事情都應該在主線程中完成。我認爲正確的順序可能是:(注意「performSelectorOnMainThread」爲addView)

-(void)myMethod{ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    UIImage *img=[UIImage imageNamed:@"animage.png"]; 
    UIImageView *imgV=[[UIImageView alloc]init]; 
    [imgV setFrame:CGRectMake(100, 100, 200, 200)]; 
    [imgV setImage:img]; 
    [self.view performSelectorOnMainThread:@selector(addSubview:) withObject:imgV waitUntilDone:YES]; 
    [imgV release]; 
    [pool release]; 
} 

希望我記得正確的。

+0

我試過了,得到了同樣的問題:如果我添加了一些其他包含在線程中等待的命令,只有在方法解析後纔會顯示圖像。那麼如何在線程結束之前進行動畫製作? – Lorenzo 2011-03-09 18:01:24

+0

...無論如何,我通過設置waitUntilDone解決了:NO。謝謝! – Lorenzo 2011-03-09 18:09:26

0

你的代碼中的一個問題是UI方法只能從主線程調用。這並不是你的問題,但你應該修正它。

你的圖像繼續顯示的原因是,你永遠不會從其超級視圖中刪除UIImageView(即通過發送它removeFromSuperview)。


編輯,響應澄清:

如果你在運行的主線程上的方法,你的UI會反應遲鈍對於sleepForTimeInterval:運行,爲UI更新10.5秒只有在「主循環」正在運行時纔會發生,並且sleepForTimeInterval:可以防止出現這種情況。也有可能出現這種情況,即阻止後臺線程的更新得到處理,或者只是在後臺線程上進行UI調用的副作用。如果您想從後臺線程調整UI,則必須使用performSelectorOnMainThread:withObject:waitUntilDone:以使方法在主線程上運行。

但是對於你在這裏要做的事情,你甚至不需要線程。只需在主線程中添加圖像視圖,並使用performSelector:withObject:afterDelay:在10.5秒後移除圖像視圖。

UIImage *img=[UIImage imageNamed:@"animage.png"]; 
UIImageView *imgV = [[[UIImageView alloc] init] autorelease]; 
[self.view addSubview:imgV]; 
[imgV setFrame:CGRectMake(100, 100, 200, 200)]; 
[imgV setImage:img]; 
[imgV performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:10.5]; 
+0

我在主UI中生成此線程。此外,我的問題是,我的圖像顯示,但方法結束時。這可以防止我用相同的方法對它進行動畫處理。 – Lorenzo 2011-03-09 17:50:25

+0

的確,您正在創建一個新線程,而不是在主線程上進行這些UI調用。 – Anomie 2011-03-09 18:10:40

+0

但是我需要偶爾生成UIImageView(例如按下按鈕)並依次生成動畫,所以我想到了一個線程。現在,用'[self.view performSelectorOnMainThread:@selector(addSubview :) withObject:imgV waitUntilDone:NO];'指令,它工作正常。 – Lorenzo 2011-03-09 18:16:11