2011-10-31 72 views
1

Basicly我在做一個圖片庫,從網上下載。下載的UIImage在「背景」

所以 - 當用戶滾動,新的圖像下載。

記住的代碼是非常 simplyfied,只是爲了告訴我是什麼意思

-(void)scrollViewDidScroll:(UIScrollView *)scrollView 
{ 
     // If new page then: 
     [self loadNextPicture]; 
} 

-(void)loadNextPicture 
{ 
    NSString *[email protected]"http://www.example.com/image.png"; 
     NSURL *imageURL = [NSURL URLWithString:url]; 
     NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; 
     UIImage *nextImage = [UIImage imageWithData:imageData]; 
     myUIImageView.image=nextImage; 

} 

我的問題是,每次用戶滾動到一個新的頁面,申請凍結了約第二次下載圖像。有沒有一種方法可以在後臺下載,以便下載時應用程序不會凍結?

上並欣賞這件事情每個想法。

安德烈亞斯:)

回答

2
[self performSelectorInBackground:@selector(loadNextPicture) withObject:nil]; 

NSObject Class Reference

+1

我想你應該設置'myUIImageView.image = NEXTIMAGE;'在'loadNextPicture主線程:'。 –

+1

真聰明! :) –

-1

你需要這樣它發生在從UI線程不同的線程具有的NSOperation做到這一點。如果您願意,可以使用AllSeeingI(http://allseeing-i.com/ASIHTTPRequest/)或AFNetworking等庫。

0

這個小類別將在後臺加載圖像,並顯示它一旦它的準備。

@interface UIImageView (BackgroundUrlImage) 
- (void)loadURL:(NSURL *)url; 
- (void)loadURLWithString:(NSString *)urlString; 
- (void)backgroundLoadURL:(NSURL *)url; 
- (void)backgroundLoadURLWithString:(NSString *)urlString; 
@end 

@implementation UIImageView (BackgroundUrlImage) 
- (void)loadURL:(NSURL *)url 
{ 
    NSError* error = nil; 
    NSData *imageData = [[NSData alloc] initWithContentsOfURL:url options:0 error:&error]; 
    // TODO: check error! 
    [imageData release]; 
    UIImage *image = [[UIImage alloc] initWithData:imageData]; 
    [self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO]; 
    [image release]; 
} 
- (void)loadURLWithString:(NSString*)urlString 
{ 
    NSURL *url = [NSURL URLWithString:urlString]; 
    if (url != nil) 
    { 
     [self loadURL:url]; 
    } 
} 
- (void)backgroundLoadURL:(NSURL *)url 
{ 
    [self performSelectorInBackground:@selector(loadURL:) withObject:url]; 
} 
- (void)backgroundLoadURLWithString:(NSString *)urlString 
{ 
    NSURL *url = [NSURL URLWithString:urlString]; 
    if (url != nil) 
    { 
     [self backgroundLoadURL:url]; 
    } 
} 
@end 

在你的示例代碼,你現在可以減少到loadNextPicture:

- (void)loadNextPicture 
{ 
    NSString *[email protected]"http://www.example.com/image.png"; 
    [myUIImageView backgroundLoadURLWithString:url]; 
} 
+0

爲什麼-1?我的代碼錯了嗎?如果是的話,我想知道,因爲我在真實項目中使用它! – squelart

0

使用NSURLConnection的異步加載數據。