Populating NSImage with data from an asynchronous NSURLConnection

后端 未结 3 966
借酒劲吻你
借酒劲吻你 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 13:37

    Your intuition is correct; you want to have a callback from the object which is the NSURLConnection’s delegate to the controller which manages the table view, which would update your data source and then call -setNeedsDisplayInRect: with the rect of the row to which the image corresponds.

    0 讨论(0)
  • 2021-02-06 14:00

    Have you tried using the initWithContentsOfURL: method?

    0 讨论(0)
  • 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.)

    0 讨论(0)
提交回复
热议问题