【问题标题】:UIImage error with dynamic string带有动态字符串的 UIImage 错误
【发布时间】:2011-07-15 17:07:59
【问题描述】:

我正在尝试将图像加载到单元格中, 以下代码工作正常:

NSString *imageURL = @"http://localhost/images/image2.jpg";
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageURL]];
UIImage *rowImage = [[UIImage alloc] initWithData:imageData];

cell.image=rowImage;

但是当我将 imageURL 更改为动态时,图像不会显示:

NSString *imageURL = [[stories objectAtIndex:indexPath.row] objectForKey:@"image"];

你可能会说问题出在:

[[stories objectAtIndex:indexPath.row] objectForKey:@"image"];

但它不是,我已经尝试记录它并且输出符合预期:

NSSLog(@"%@",[[stories objectAtIndex:indexPath.row] objectForKey:@"image"]);
//Outputs http://localhost/images/image2.jpg

可能出了什么问题?

【问题讨论】:

  • 看起来不错。你从哪里得到stories 数组?
  • 它来自XMLParser委托方法,但它已经输出了值。

标签: objective-c xcode ios4 iphone-sdk-3.0


【解决方案1】:

我猜在字符串之前或之后有空格。就这样吧,

NSString *imageURL = [[stories objectAtIndex:indexPath.row] objectForKey:@"image"];
imageURL = [imageURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageURL]];
UIImage *rowImage = [[UIImage alloc] initWithData:imageData];

虽然这应该主要解决您的问题,但我建议您在 XML 解析期间添加到字典之前修剪字符串。

您还应该确保同时发布imageDatarowImage。您可能已经这样做了,但它不在上面的代码中,所以我只想指出它可能会泄漏。

【讨论】:

    【解决方案2】:

    试试这个

        NSString *imageURL =[NSString stringWithFormat:@"%@",[[stories objectAtIndex:indexPath.row] objectForKey:@"image"]];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 2015-07-03
      • 1970-01-01
      相关资源
      最近更新 更多