【问题标题】:How to add UIImage object into NSMutableArray in iOS如何在 iOS 中将 UIImage 对象添加到 NSMutableArray
【发布时间】:2015-08-29 23:07:05
【问题描述】:

我正在尝试将 UIImage 对象添加到数组中,但它们没有被添加。请帮忙

我的代码:

imageArray = [[NSMutableArray alloc] init];
arry = [[NSMutableArray alloc] init];

[arry addObject:@"http://adjingo.2cimple.com/content/151/Image/6291.jpg"];
[arry addObject:@"http://adjingo.2cimple.com/content/151/Image/6290.jpg"];

//Fetch images from web and store in another array
for (int i=0; i<[arry count]; i++)
{
    NSString *string=[arry objectAtIndex:i];
    NSURL *url=[NSURL URLWithString:string];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                           if ( !error )
                           {
                               UIImage *image = [[UIImage alloc] initWithData:data];

                               //Store image in imageArray
                               [imageArray insertObject:image atIndex:i];

                           } else{

                           }
                       }];
}

NSLog(@"%lu",(unsigned long)[imageArray count]); //this line is always showing 0 as count

当我打印包含UIImage 对象的数组的count 时,它显示0

(我实际上想以数组形式一次下载图像,然后以幻灯片形式显示UIImageView)。

请指导我。谢谢!

【问题讨论】:

  • 您可以先将该图像转换为 NSData,然后将该数据添加到数组中。
  • @RajatDeepSingh 1. 注意接收到的图像 NSData 对象。 2.将NSImage对象保存在NSMutableArray中没有问题,只是数组中的指针。
  • @zaph ,请在下面查看我对您的回答的评论。

标签: ios objective-c uiimageview uiimage nsmutablearray


【解决方案1】:

有几个问题。

  1. [[NSMutableArray alloc] init] 不分配内存,并且无法添加超出当前大小的项目。 [NSMutableArray arrayWithCapacity:size] 确实分配了内存,并且对象可以插入到任何索引处,包括当前大小。请参阅NSMutableArray 文档。

  2. sendAsynchronousRequest 块之后立即没有下载任何图像,下载完成后会发生这种情况。

  3. 同时开始大量下载可能会出现性能问题。

【讨论】:

  • 感谢您的帮助。我想通知一次不会有任何大量下载,因为 1. 图像将是小尺寸的,2. 只有 2 - 4 个图像将在那里。其次,我也尝试过使用SDWebImageManager,但遇到了问题there,所以我想采用这种更简单的方式。你能详细说明你的第一点吗?是的,您对第 2 点是正确的。但是我应该在哪里添加它们到我的数组中?问候
  • WRT点1,将imageArray的分配方式改为arrayWithCapacity:。您正在添加图像,只是它们将在以后可用。当它们实际收到时,您可以在块中执行某些操作,根据您对它们的使用情况触发通知或其他操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多