我想使用PHImagemanager来获取设备上的所有照片。 如果我将目标大小设置得太高,应用程序将因内存警告而崩溃。所以我测试了请求而没有使用返回的图像并将每个图像设置为nil,但仍然app崩溃。我不知道自己做错了什么。有人可以帮忙吗?
<FlatList>
大约200张图像后将尺寸设置为640x480,大约800张图像后将尺寸设置为320x240。由于640x480图像需要4倍内存然后需要320x240图像,因此应用程序会在分配相同数量的内存后崩溃。所以对我来说,这意味着我无法在测试设备上显示比使用640x480的200个图像更多的图像,因为我无法释放已分配的内存。
答案 0 :(得分:0)
为了使@autoreleasepool
工作,您需要将requestOptions.synchronous
设置为YES
,并且如果要异步进行请求操作,请使用您自己的异步队列。
答案 1 :(得分:-1)
请在for循环中使用@autoreleasepool。
for (int i = 0; i <= totalImages - 1; i++) {
@autoreleasepool {
//Your code
}
}
答案 2 :(得分:-1)
如果你想加载你在Photos.app中拥有的所有照片而你并不想要iCloud。你可以这样做:
该示例适用于集合视图。
@interface GalleryViewModel ()
@property (strong, nonatomic) NSMutableArray<PHAsset *> *assets;
@property (strong, nonatomic) PHImageManager *imageManager;
@property (strong, nonatomic) PHImageRequestOptions *requestOptions;
@property (strong, nonatomic) NSMutableArray<UIImage *> *imagesList;
@end
@implementation GalleryViewModel
- (instancetype) initWithContext:(ITXAppContext *)context {
self = [super initWithContext:context];
if (self) {
_assets = [[NSMutableArray alloc] init];
_imageManager = [PHImageManager defaultManager];
_requestOptions = [[PHImageRequestOptions alloc] init];
_imagesList = [[NSMutableArray alloc] init];
}
return self;
}
#pragma mark - Public methods
// ==================================================================================
// Public methods
- (void) viewModelDidLoad {
[self obtainAllPhotos];
}
#pragma mark - Private methods
// ==================================================================================
// Private methods
- (void) obtainAllPhotos {
self.requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
self.requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
self.requestOptions.synchronous = YES;
self.requestOptions.networkAccessAllowed = NO;
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
PHFetchResult<PHAsset *> *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
__weak GalleryViewModel *weakSelf = self;
[result enumerateObjectsUsingBlock:^(PHAsset * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[weakSelf.assets addObject:obj];
if (idx >= ([result count] - 1)) {
[weakSelf.viewDelegate setupView];
}
}];
}
#pragma mark - Get data from object
// ==================================================================================
// Get data from object
- (NSInteger) sizeGallery {
if (self.assets) {
return [self.assets count];
}
return 0;
}
- (UIImage *) imagesFromList:(NSInteger) index {
__block UIImage *imageBlock;
[self.imageManager requestImageForAsset:[self.assets objectAtIndex:index] targetSize:CGSizeMake(200, 200) contentMode:PHImageContentModeAspectFit options:self.requestOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
if (result) {
imageBlock = result;
}
}];
return imageBlock;
}
@end