【问题标题】:NSData returning 0 bytesNSData 返回 0 个字节
【发布时间】:2012-04-15 08:56:26
【问题描述】:

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

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; 

}

【问题讨论】:

  • 你确定你确实收到了来自 url 的数据吗?
  • 是的,正在接收数据...但无法访问我的 tableview 函数中的数据...

标签: iphone ios objective-c xcode ios5


【解决方案1】:

您对异步性感到困惑。如果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;
}

查看URL Loading System Programming Guide on NSURLConnection 了解更多详情/示例。

【讨论】:

  • 非常感谢 Kristian 的友好回复,但我怎么能在我的 connectionDidFinishLoading 函数中访问我的 tableview 单元格?...已将单元格声明为全局,但它没有用..:(
  • 啊,我想知道你是否会这么问。每个cell 都需要一个delta,并且从每个连接开始到这两个的映射。我会尽力为你挖掘一个例子。
  • Christian 非常感谢您的帮助...我已经在...的帮助下解决了这个问题...markj.net/iphone-asynchronous-table-image
  • ...那段代码的编写存在一些非常基本的误解,我对此有些不服...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
  • 2012-07-26
相关资源
最近更新 更多