上一篇:我正在尝试获取相机胶卷中的照片数量,我开始使用积木但遇到了一些困难。
现在:这是我更新的代码,我正在使用异步行为,但在我的块有机会完成之前返回一个值。
#import "CoverViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
@interface CoverViewController () <UITextFieldDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property(nonatomic, weak) IBOutlet UICollectionView *collectionView;
@property (assign) NSUInteger numberOfPhotos;
@end
@implementation CoverViewController
@synthesize CoverView;
- (void)viewWillAppear:(BOOL)animated
{
NSLog(@"viewWillAppear");
[self beginLoadingPhotoInfo];
}
//Photo collection info
- (void)beginLoadingPhotoInfo {
NSLog(@"loaded beginloadingphotoinfo");
__weak CoverViewController *__self = self;
[self PhotoCount:^(NSUInteger photoCount) {
__self.numberOfPhotos = photoCount;
}];
//[__self.CoverView reloadData];
}
- (void)PhotoCount:(void(^)(NSUInteger))completionBlock {
NSLog(@"photo count start");
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
__block NSInteger result = 0;
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop){
if(group != nil) {
NSLog(@"if");
result += [group numberOfAssets];
NSLog(@"enum: %d", result);
}
else {
NSLog(@"else");
//nil means we are done with enumeration
if (completionBlock) {
completionBlock(result);
}
}
};
[library enumerateGroupsWithTypes: ALAssetsGroupSavedPhotos
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {NSLog(@"Problems");}
];
NSLog(@"result: %u", result);
}
// Layout of collection
//Number of cells in collection
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
NSLog(@"returned number: %d", self.numberOfPhotos);
return self.numberOfPhotos;
}
@end
我已经在我的coverviewcontroller.h 文件中添加了所有相关的内容,但代码似乎在块完成之前加载。这是我查找错误的尝试,它表明 photoCount 在我的块完成之前返回 0。
2013-07-27 21:16:00.986 slidr[1523:c07] viewWillAppear
2013-07-27 21:16:00.987 slidr[1523:c07] loaded beginloadingphotoinfo
2013-07-27 21:16:00.987 slidr[1523:c07] photo count start
2013-07-27 21:16:00.988 slidr[1523:c07] result: 0
2013-07-27 21:16:00.989 slidr[1523:c07] returned number: 0
2013-07-27 21:16:01.012 slidr[1523:c07] if
2013-07-27 21:16:01.013 slidr[1523:c07] enum: 3
2013-07-27 21:16:01.014 slidr[1523:c07] else
有任何想法吗?