views:

98

answers:

1

Hi all,

I am using the code below to set images in a table which are loaded from the server, but I have an exception thrown (not every time) which is related to a drawing error

- (void) getTheThumnbails:(NSIndexPath *)indexPath{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    GDataEntryYouTubeVideo *entry = [feedArray objectAtIndex:indexPath.row];

    NSURL *url = [[NSURL alloc] initWithString:[[[[entry mediaGroup] mediaThumbnails] objectAtIndex:0] URLString]];
    NSData *imgData = [[NSData alloc] initWithContentsOfURL:url];
    UIImage *img = [[UIImage alloc] initWithData:imgData];

    CGRect newFrame = CGRectMake(0.0, 0.0, 62.0, 62.0);

    UIGraphicsBeginImageContext(newFrame.size);

    [img drawInRect:newFrame];

    UIImage *resizedImg = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    [imgDict setObject:resizedImg forKey:[NSString stringWithFormat:@"%i",indexPath.row]];

    [[[myTableView cellForRowAtIndexPath:indexPath] imageView] setImage:resizedImg];
    [pool release];
}

Please help me folks, sorting out the mistake i am doing.

A: 

Hey you are trying to draw a image in a thread which is not a good practice, please do not perform any UI operations in thread, they need to be done in the main thread.

well you can do the above like

- (void) getTheThumnbails:(NSIndexPath *)indexPath{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    GDataEntryYouTubeVideo *entry = [feedArray objectAtIndex:indexPath.row];

    NSURL *url = [[NSURL alloc] initWithString:[[[[entry mediaGroup] mediaThumbnails] objectAtIndex:0] URLString]];
    NSData *imgData = [[NSData alloc] initWithContentsOfURL:url];
    UIImage *img = [[UIImage alloc] initWithData:imgData];
    [imgDict setObject:img forKey:[NSString stringWithFormat:@"%i",indexPath.row]];
    [img release];
    [self performSelectorOnMainThread:@selector(setImageInTable:) withObject:indexPath waitUntilDone:NO];
    [pool release];
}

- (void)setImageInTable:(NSIndexPath *)indexPath{

    UIImage *img = (UIImage *)[imgDict valueForKey:[NSString stringWithFormat:@"%i",indexPath.row]];

    CGRect newFrame = CGRectMake(0.0, 0.0, 62.0, 62.0);

    UIGraphicsBeginImageContext(newFrame.size);

    [img drawInRect:newFrame];

    UIImage *resizedImg = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    [imgDict removeObjectForKey:[NSString stringWithFormat:@"%i",indexPath.row]];

    [imgDict setObject:resizedImg forKey:[NSString stringWithFormat:@"%i",indexPath.row]];

    [[[myTableView cellForRowAtIndexPath:indexPath] imageView] setImage:resizedImg];

}

Hope this helps.

Thanks,

Madhup

Madhup