如何创建UIImages数组

时间:2015-08-08 19:26:48

标签: ios objective-c parse-platform uiimage

我正在存储来自Parse数据库的图像,如下所示:

PFFile *firstImageFile = self.product[@"firstThumbnailFile"];
[firstImageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
    if (!error) {
        self.firstImage = [UIImage imageWithData:imageData];
    }
}];

我想将图像保存为数组,以便在滚动视图中显示它们。

如果我做这样的事情就行了:

self.galleryImages = [NSArray arrayWithObjects: [UIImage imageNamed:@"s2.jpg"], [UIImage imageNamed:@"s1.jpg"], nil];

但如果我尝试使用UIImage本身,则不会出现图像。

self.galleryImages = [NSArray arrayWithObjects: self.firstImage, self.secondImage, nil];

有任何帮助吗?感谢。

2 个答案:

答案 0 :(得分:1)

这是一个常见问题的形式:如何执行许多异步操作(没有深度嵌套完成块)并知道它们何时完成。我使用的方法是将操作的参数视为待办事项列表,并构建一个递归处理列表的方法....

- (void)loadPFFiles:(NSArray *)array filling:(NSMutableDictonary *)results completion:(void (^)(BOOL))completion {
    NSInteger count = array.count;
    // degenerate case is an empty array which means we're done
    if (!count) return completion(YES);

    // otherwise, do the first operation on the to do list, then do the remainder
    PFFile *file = array[0];
    NSArray *remainder = [array subarrayWithRange:NSMakeRange(0, count-1)];

    [file getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
        if (!error) {
            UIImage *image = [UIImage imageWithData:imageData];
            results[file.name] = image;
            [self loadPFFiles:remainder filling:results completion:completion];
        } else {
            completion(NO);
        }
    }];
}

这样称呼(猜测一下你的模型):

NSArray *pfFiles = @[ self.product[@"firstThumbnailFile"], self.product[@"secondThumbnailFile"] ];
NSMutableDictionary *result = [@{} mutableCopy];

[self loadPFFiles:pfFiles filling:result completion:^(BOOL success) {
    if (success) {
        // result will be an dictionary of the loaded images
        // indexed by the file names
    }
}];

答案 1 :(得分:0)

我猜(基于你对上面的nil的评论)你的代码看起来有点像这样:

PFFile *firstImageFile = self.product[@"firstThumbnailFile"];
[firstImageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
    if (!error) {
        self.firstImage = [UIImage imageWithData:imageData];
    }
}];

self.galleryImages = [NSArray arrayWithObjects: self.firstImage, self.secondImage, nil];

如果是这种情况,请在完成块内移动数组初始化,如下所示:

PFFile *firstImageFile = self.product[@"firstThumbnailFile"];
[firstImageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
    if (!error) {
        self.firstImage = [UIImage imageWithData:imageData];

        dispatch_async(dispatch_get_main_queue(), ^{

                self.galleryImages = [NSArray arrayWithObjects: self.firstImage, self.secondImage, nil];
            });
    }
}];

在第一个(你的)情况下发生的事情是数组初始化语句在完成块之前运行,所以当第一个图像'实际设置为时已晚,因为数组已经初始化。

相关问题