繁体   English   中英

NSData返回0字节

[英]NSData returning 0 bytes

我正在尝试以以下方式加载图像。 但是,当我在我的tableView [self loadImagesFromURL:url]我的loadImageFromURL:(NSURL*)inURL函数称为[self loadImagesFromURL:url] ,它显示0个字节。 如何在我的tableview获取(delta)NSData的值?该值声明为global ...

NSURLConnection* connection;
NSMutableData* delta;

- (void)loadImageFromURL:(NSURL*)inURL {
    NSURLRequest *request = [NSURLRequest requestWithURL:inURL];
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];

    if (conn) {
        delta = [[NSMutableData data] retain];
    }    
}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data {
    [delta appendData:data];

    }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {     
    NSURL *urlink=[NSURL URLWithString:[[objectsForImages objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]];
    [self loadImageFromURL:urlink];
    UIImage *imageForAz=[UIImage imageWithData:delta];
    cell.imageView.image=imageForAz; 

}

您对异步性感到困惑。 如果loadImageFromURL:是同步的,例如包装sendSynchronousRequest:returningResponse:error:您的代码将按预期工作; loadImageFromURL:在获取时将阻塞,并在填充delta时返回。

但是,这都是异步的,因此您实际需要做的是在您的委托中实现connectionDidFinishLoading:在本例中为self ),并在其中设置cell.imageView.image

相应地重写一些代码(出于此示例的目的,我假设您删除了tableView:cellForRowAtIndexPath:中的无关代码):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {     
    NSURL *urlink=[NSURL URLWithString:[[objectsForImages objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]];
    [self loadImageFromURL:urlink];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    UIImage *imageForAz=[UIImage imageWithData:delta];
    cell.imageView.image=imageForAz;
}

有关更多详细信息/示例,请参阅NSURLConnection上URL加载系统编程指南

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM