2012-10-26 5 views
0

웹에서 이미지를 다운로드하는 함수를 작성했습니다. 블록을 인수로 사용합니다. 모든 것이 메모리 캐싱을 추가 할 때까지 제대로 작동했습니다. 이미지가 캐시에서 alredy 인 경우 함수는 반환하지 않습니다 (그러나 블록은 0이 아닙니다).블록을 인수로 사용하는 함수는 항상 반환하지 않습니다.

- (void) downloadImageFromURL:(NSURL *) url completionBlock:(void (^)(UIImage *image, NSError *error)) block { 

dataHandler = [DataHandler sharedInstance]; 

UIImage *img=[dataHandler.avatarImages objectForKey:[url absoluteString]]; 
//image is in cache 
if (img) { 
    block(img, nil); 
} 
//not in cache, download it (works ok) 
else { 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{ 
     NSData *imageData = [NSData dataWithContentsOfURL:url]; 
     UIImage *picture=[UIImage imageWithData:imageData]; 
     if(picture) { 
      //save to cache 
      [dataHandler.avatarImages setObject:picture forKey:[url absoluteString]]; 
      block(picture, nil); 
     } 
     else { 
      NSError *error = [NSError errorWithDomain:@"image_download_error" code:1 
              userInfo:[NSDictionary dictionaryWithObject:@"Can't fetch data" forKey:NSLocalizedDescriptionKey]]; 
      block(nil, error); 
     } 

    }); 
} 

블록은 다음과 같이 호출됩니다

 ImageDownloader *idl=[[ImageDownloader alloc] init]; 

     NSURL *imageUrl=[NSURL URLWithString:ta.avatarUrl]; 
     [idl downloadImageFromURL:imageUrl completionBlock:^(UIImage *image, NSError *error) 
     { 
      if(!error) { 
       dispatch_async(dispatch_get_main_queue(), ^(void) { 
        logo.image=image; 
       }); 
      } else { 
       NSLog(@"error %@", error); 
      } 

     }]; 
+0

블록은? – shem

답변

0

변화 블록에 전화 캐시의 이미지는 다음과 같이 할 때

if (img) { 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     block(img, nil); 
    }); 
} 

사용자는 경우 신경 안 이미지를 캐시에 저장할지 여부를 결정해야하며, 어떤 경우에는 블록을 비동기라고해야합니다.

관련 문제