数组保存的照片总是返回为空
问题描述:
我试图从保存的相册中创建一个匹配特定条件的所有图像的数组。这是一个简化的代码。我将这些照片添加到myImages数组中,并通过“已添加图像”日志进行确认,以便记录正确的图像。但是函数返回的数组总是空的。相当新的Objective-C,所以任何建议都会有帮助。数组保存的照片总是返回为空
NSMutableArray * myImages = [NSMutableArray array];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Enumerate just the photos by using ALAssetsGroupSavedPhotos.
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
// Within the group enumeration block, filter to enumerate just photos.
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
[group enumerateAssetsUsingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) {
// The end of the enumeration is signaled by asset == nil.
if (alAsset) {
ALAssetRepresentation *representation = [alAsset defaultRepresentation];
UIImage *latestPhoto = [UIImage imageWithCGImage:[representation fullResolutionImage]];
NSLog(@"Added Image");
[myImages addObject:latestPhoto];
}
}];
}
failureBlock: ^(NSError *error) {
// Typically you should handle an error more gracefully than this.
NSLog(@"No groups");
}];
return myImages;
答
什么是imageTakenOnDate?那应该是myImages?如果是这样,你不能以这种方式返回它,因为该方法返回之后,块代码将执行。该方法是异步的。选项1:让你的方法以一个完成块作为参数,然后调用enumerateGroupsWithTypes块内的完成块,然后再调用完成块,并传递完成块数组。例如:
typedef void (^CompletionBlock)(id, NSError*);
-(void)myMethodWithCompletionBlock:(CompletionBlock)completionBlock;
然后当你与成功调用来完成:
completionBlock(myImages, nil);
,并在failureBlock电话:
completionBlock(nil, error);
选项2:使数组的伊娃是保留在父对象上,而不是局部变量,然后将其声明为__block变量,以便可以在块内修改它。
答
第一件事。你真的返回imagesTakenOnDate?在代码中看不到任何对此ivar的引用。我会说你在你的代码中加入了一些断点。在gdb调试器控制台中你可以输入:
po myImages
比调试器会打印出你的数组的内容。希望有帮助
是的,imagesTakenOnDate应该是myImages。我会阅读你的建议并尝试。谢谢! – vishwa