Populating NSImage with data from an asynchronous NSURLConnection

后端 未结 3 968
借酒劲吻你
借酒劲吻你 2021-02-06 13:33

I have hit the proverbial wall trying to figure out how to populate an NSImage with data returned from an asynchronous NSURLConnection in my desktop app (NOT an iPhone applicati

3条回答
  •  温柔的废话
    2021-02-06 14:02

    My solution is to use Grand Central Dispatch (GCD) for this purpose, you could save the image to disc too in the line after you got it from the server.

    - (NSView *)tableView:(NSTableView *)_tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
    {
        SomeItem *item = [self.items objectAtIndex:row];
        NSTableCellView *cell = [_tableView makeViewWithIdentifier:tableColumn.identifier owner:self];
        if (item.artworkUrl)
        {
            cell.imageView.image = nil;
            dispatch_async(dispatch_queue_create("getAsynchronIconsGDQueue", NULL), 
            ^{
                NSURL *url = [NSURL URLWithString:item.artworkUrl];
                NSImage *image = [[NSImage alloc] initWithContentsOfURL:url];
                cell.imageView.image = image;        
            });
        }
        else
        {
            cell.imageView.image = nil;    
        }
        return cell;
    }
    

    (I am using Automatic Reference Counting (ARC) therefore there are no retain and release.)

提交回复
热议问题