【问题标题】:Creating UIImage array创建 UIImage 数组
【发布时间】:2014-08-19 01:49:34
【问题描述】:

我编写了从 JSON 请求中收集图像并尝试将它们添加到 NSMutableArray 的代码,以便稍后在表格视图中使用。问题是在将图像对象添加到数组后,我的NSMutableArray的大小为0。下面是相关代码:

@implementation example{
    NSMutableArray *_placeImages;
}

-(void)viewDidLoad{
    ...
    _placeImages = [[NSMutableArray alloc] init];
}

-(void)JsonQuery {
    ...
    // Retrieve the results of the URL.
    dispatch_async(kMyQueue, ^{
    [self downloadImages];
    [self performSelectorOnMainThread:@selector(reloadTableData) withObject:NULL waitUntilDone:YES];
    });
}

-(void)downloadImages{
     ...
     NSData* data = [NSData dataWithContentsOfURL: url];
    UIImage* image = [UIImage imageWithData:data];
    [_placeImages addObject:image];
}

【问题讨论】:

  • 你有没有在任何地方初始化你的数组? _placeImages = [NSMutableArray new]
  • 是的!我忘了添加那一点,但我做了[[NSMutableArray alloc] init]。我想知道它是否与从另一个线程访问数组有关。
  • 不管您当前的问题,您在这里所做的并不是收集和显示图像的正确方法。我建议你应该使用SDWebImage 让图像显示在 UITableView 上。它易于部署和使用。几乎每个人都将它用于 UITableView + Image 组合。它有自己的缓存机制,你不需要一次又一次地下载相同的图像。
  • 感谢@mohacs 的提示。
  • @SevP 你确定viewDidLoad 正在解雇之前 downloadImages

标签: ios objective-c uiimage nsmutablearray


【解决方案1】:

你必须先分配 NSMutableArray:

_placeImages = [[NSMutableArray alloc] init];

或者你可以使用惰性初始化:

- (NSMutableArray *)placeImages
{
    if (!_placeImages) {
       _placeImages = [[NSMutableArray alloc] init];
    }
    return _placeImages
}

【讨论】:

  • 感谢您的回复。我实际上在我的 viewDidLoad 方法中做了 alloc 和 init,但这肯定是个问题。
  • 如果没有必要使用 NSMutableAarray,我推荐你使用 NSArray,因为 NSMutableArray 没有线程安全的。此外,使用惰性初始化将 _placeImages 声明为属性,并且只能使用 self.placeImages 访问它。希望这可以帮助你,祝你好运。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-24
  • 2012-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多