2011-06-27 45 views
0

好吧,現在我正在像餐廳取景器的移動應用程序,我想表明這家飯店的照片如何製作簡單的多線程?

的例子:restaurant x <image x>

這是一個代碼:

if (ImageToDisplay != nil) 
{ 
    NSData * imageData = [[[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: ImageToDisplay.URL]]autorelease]; 
    ImageForRestaurant.image = [UIImage imageWithData: imageData]; 
} 

的問題是這個下載圖片的過程可能需要很長時間。所以我想讓這個過程在不同的線程上運行。

這種方式後,代碼可以運行,而無需等待這一個完成。

我該怎麼做?

回答

3
if (ImageToDisplay != nil) { 
    [self performSelectorInBackground:@selector(loadImage:) object:ImageToDisplay]; 
} 

- (void)loadImage:(ImageToDisplay *)image { //Background method 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    NSData * imageData = [[[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: ImageToDisplay.URL]]autorelease]; 
    [self performSelectorOnMainThread:@selector(setImageForRestaurant:) withObject:imageData waitUntilDone:NO]; 
    [pool release]; 
} 

- (void)setImageForRestaurant:(NSData *)imageData { //Change UI in main thread 
    ImageForRestaurant.image = [UIImage imageWithData: imageData]; 
} 

我剛纔介紹了多線程的基礎知識;我想這將用於你的目的

+0

loadImage中的自動釋放是什麼? –

+0

有沒有叫ImageToDisplay的類 –

+0

爲什麼這個代碼:[self performSelectorInBackground:@selector(loadImage :) loadImage:ImageToDisplay];不工作。我在標題中添加了導入NSTread,但它表示未找到標題。你能給我一個NSTread的框架嗎?是否需要NSTread.h? –

2

使用ASIHTTPRequest庫。見'創建異步請求'本頁:http://allseeing-i.com/ASIHTTPRequest/How-to-use

此外,新庫AFNetworking看起來很有希望。正如他們所說:

如果你厭倦了試圖做太多,大量的庫,如果你已經採取它在自己推出自己的解決方案哈克,如果你想,實際上使得iOS的網絡圖書館代碼有點兒有趣,試試AFNetworking。

+1

@Armen [re:edit]我覺得URL比「本頁」更具描述性。它在語義上是正確的和內容豐富的。 – Ross

2

你嘗試

- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg

我認爲這是最簡單的方法。