PHAsset fetchAssetsInAssetCollection 报 malloc_error

本文详细解析了iOS应用中使用PHFetchResult时遇到的崩溃问题,特别是在iOS12.1.2和12.1.4版本上。通过分析崩溃日志,发现多线程环境下内存分配冲突是导致问题的根本原因。最终通过加锁解决了该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

查看崩溃日志,发现有几条崩溃记录是选相册的崩溃,崩溃日志如下:


#0 Thread
SIGABRT
0 libsystem_kernel.dylib	__pthread_kill + 8
1 libsystem_pthread.dylib	_pthread_kill$VARIANT$mp + 380
2 libsystem_c.dylib	abort + 140
3 libsystem_malloc.dylib	__malloc_put
4 libsystem_malloc.dylib	_malloc_report + 64
5 libsystem_malloc.dylib	free + 376
6 CoreFoundation	0x00000001df485000 + 13464
7 **********	__37-[HXPhotoManager fetchAlbums:albums:]_block_invoke.192 (HXPhotoManager.m:376)
8 CoreFoundation	0x00000001df485000 + 1028784
9 CoreFoundation	0x00000001df485000 + 1030320
10 libdispatch.dylib	__dispatch_client_callout2 + 16
11 libdispatch.dylib	__dispatch_apply_invoke_and_wait + 164
12 libdispatch.dylib	_dispatch_apply_f$VARIANT$mp + 720
13 CoreFoundation	0x00000001df485000 + 1029888
14 Photos	-[PHFetchResult enumerateObjectsWithOptions:usingBlock:] + 88
15 **********	-[HXPhotoManager fetchAlbums:albums:] (HXPhotoManager.m:0)
16 **********	-[HXDatePhotoViewController getAlbumList] (HXDatePhotoViewController.m:379)
17 **********	__40-[HXDatePhotoViewController viewDidLoad]_block_invoke_2 (HXDatePhotoViewController.m:117)
18 libdispatch.dylib	__dispatch_call_block_and_release + 24
19 libdispatch.dylib	__dispatch_client_callout + 16
20 libdispatch.dylib	__dispatch_main_queue_callback_4CF$VARIANT$mp + 1068
21 CoreFoundation	0x00000001df485000 + 707812
22 CoreFoundation	0x00000001df485000 + 687020
23 CoreFoundation	CFRunLoopRunSpecific + 436
24 GraphicsServices	GSEventRunModal + 100
25 UIKitCore	UIApplicationMain + 212
26 **********	main (main.m:17)
27 libdyld.dylib	_start + 4
复制代码

查看那个地方的代码,

// 是否按创建时间排序
    PHFetchOptions *option = [[PHFetchOptions alloc] init];
    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    if (self.type == HXPhotoManagerSelectedTypePhoto) {
        option.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld", PHAssetMediaTypeImage];
    }else if (self.type == HXPhotoManagerSelectedTypeVideo) {
        option.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld", PHAssetMediaTypeVideo];
    }
// 获取用户相册
    PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
    [userAlbums enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL * _Nonnull stop) {
        // 获取照片集合
        PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:option];
        
        // 过滤掉空相册
        if (result.count > 0) {
            HXAlbumModel *albumModel = [[HXAlbumModel alloc] init];
            albumModel.count = result.count;
            albumModel.albumName = [HXPhotoTools transFormPhotoTitle:collection.localizedTitle];
            albumModel.result = result;
            [self.albums addObject:albumModel];
        }
    }];
复制代码

也都还正常没有发现问题。 仔细查找崩溃记录,发现现有的记录 崩溃的设备都集中在 iOS 12.1.2 和12.1.4,部分12.0和12.0.1也有,而自己的 iOS12.1.4和 iOS12.1.2 还有 iOS12.0 都复现不了。难道又是 iOS 的坑么?

后来又仔细看了下其他线程,发现还有一个线程也在读取相册:


#10 Thread
0 libsystem_kernel.dylib	0x00000001df12bea4 mach_msg_trap
1 libsystem_kernel.dylib	0x00000001df12b37c mach_msg
2 libdispatch.dylib	0x00000001def902d0 __dispatch_mach_send_and_wait_for_reply
3 libdispatch.dylib	0x00000001def90764 _dispatch_mach_send_with_result_and_wait_for_reply$VARIANT$mp
4 libxpc.dylib	0x00000001df1f3ea0 xpc_connection_send_message_with_reply_sync
5 Foundation	0x00000001e0166ab8 0x00000001dff1a000
6 Foundation	0x00000001dff2e56c 0x00000001dff1a000
7 Foundation	0x00000001dff3c334 0x00000001dff1a000
8 Foundation	0x00000001e016ca64 0x00000001dff1a000
9 CoreData	0x00000001e20de474 -[NSXPCStoreConnection sendMessage:store:error:]
10 CoreData	0x00000001e20de320 -[NSXPCStoreConnection sendMessageWithContext:]
11 CoreData	0x00000001e22c42b8 ___54-[NSXPCStoreConnectionManager sendMessageWithContext:]_block_invoke
12 libdispatch.dylib	0x00000001defda484 __dispatch_client_callout
13 libdispatch.dylib	0x00000001def87bd4 __dispatch_sync_invoke_and_complete
14 CoreData	0x00000001e20ddcac -[NSXPCStoreConnectionManager sendMessageWithContext:]
15 CoreData	0x00000001e20dd494 -[NSXPCStore sendMessage:fromContext:interrupts:error:]
16 CoreData	0x00000001e20d3940 -[NSXPCStore executeFetchRequest:withContext:error:]
17 CoreData	0x00000001e20d2b18 -[NSXPCStore executeRequest:withContext:error:]
18 CoreData	0x00000001e2229de4 ___65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke
19 CoreData	0x00000001e20bb254 -[NSPersistentStoreCoordinator _routeHeavyweightBlock:]
20 CoreData	0x00000001e20bbee4 -[NSPersistentStoreCoordinator executeRequest:withContext:error:]
21 CoreData	0x00000001e20c447c -[NSManagedObjectContext executeFetchRequest:error:]
22 PhotoLibraryServices	0x00000001ed399224 -[PLManagedObjectContext executeFetchRequest:error:]
23 Photos	0x00000001ee3dc07c ___55+[PHFetchResult fetchObjectIDs:inManagedObjectContext:]_block_invoke
24 CoreData	0x00000001e21fae88 _developerSubmittedBlockToNSManagedObjectContextPerform
25 libdispatch.dylib	0x00000001defda484 __dispatch_client_callout
26 libdispatch.dylib	0x00000001def8799c __dispatch_sync_invoke_and_complete_recurse
27 libdispatch.dylib	0x00000001def874a0 __dispatch_sync_f_slow
28 CoreData	0x00000001e20c28b8 -[NSManagedObjectContext performBlockAndWait:]
29 Photos	0x00000001ee3dbca4 +[PHFetchResult fetchObjectIDs:inManagedObjectContext:]
30 Photos	0x00000001ee3dccfc ___57-[PHFetchResult fetchedObjectsUsingManagedObjectContext:]_block_invoke
31 AssetsLibraryServices	0x00000001ecf8378c ___pl_dispatch_sync_block_invoke
32 libdispatch.dylib	0x00000001defda484 __dispatch_client_callout
33 libdispatch.dylib	0x00000001def875c8 __dispatch_lane_barrier_sync_invoke_and_complete
34 AssetsLibraryServices	0x00000001ecf8375c pl_dispatch_sync
35 Photos	0x00000001ee3dcbf4 -[PHFetchResult fetchedObjectsUsingManagedObjectContext:]
36 Photos	0x00000001ee3da4c0 -[PHFetchResult initWithQuery:oids:registerIfNeeded:usingManagedObjectContext:]
37 Photos	0x00000001ee3da5fc -[PHFetchResult initWithQuery:]
38 Photos	0x00000001ee384e30 -[PHQuery executeQuery]
39 Photos	0x00000001ee323c3c +[PHAsset fetchAssetsInAssetCollection:options:]
40 **********	0x0000000102657198 __37-[HXPhotoManager fetchAlbums:albums:]_block_invoke.192 (HXPhotoManager.m:0)
41 CoreFoundation	0x00000001df5802b0 0x00000001df485000
42 CoreFoundation	0x00000001df5808b0 0x00000001df485000
43 libdispatch.dylib	0x00000001defda4c4 __dispatch_client_callout2
44 libdispatch.dylib	0x00000001def8b7fc __dispatch_apply_invoke$VARIANT$mp
45 libdispatch.dylib	0x00000001defda484 __dispatch_client_callout
46 libdispatch.dylib	0x00000001def89b4c __dispatch_root_queue_drain
47 libdispatch.dylib	0x00000001def8a2c0 __dispatch_worker_thread2
48 libsystem_pthread.dylib	0x00000001df1bd17c _pthread_wqthread
复制代码

查了一些资料,估计是因为多线程造成内存分配冲突的原因,于是给 PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:option]; 这个方法加锁,然后问题就消失了。

代码如下:

// 获取用户相册
    PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
    [userAlbums enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL * _Nonnull stop) {
        // 获取照片集合
        // 在 iOS 12.0 12.1 12.1.2 12.1.4 上,这个地方会报 malloc_error 错误,
        // enumerateObjectsWithOptions 这个 block 会分2个线程回调,估计是多线程造成内存冲突的原因,所以这里加上一个线程锁。
        [self.fetchAlbumsLock lock];
        PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:option];
        
        // 过滤掉空相册
        if (result.count > 0) {
            HXAlbumModel *albumModel = [[HXAlbumModel alloc] init];
            albumModel.count = result.count;
            albumModel.albumName = [HXPhotoTools transFormPhotoTitle:collection.localizedTitle];
            albumModel.result = result;
            [self.albums addObject:albumModel];
        }
        [self.fetchAlbumsLock unlock];
    }];
复制代码

这个问题出现的确实比较诡异,有些手机比较容易出现,有些就是出现不了。而PHFetchResultenumerateObjectsWithOptions这个方法,苹果的文档上面并没有说明是多线程回调的。真是个大坑。

参考文章

my.oschina.net/CrazyPeter/…

转载于:https://juejin.im/post/5c6e7b0451882524c84f1da4

github地址: https://github.com/LoveZYForever/HXWeiboPhotoPicker 一. 安装 手动导入:将项目中的“HXWeiboPhotoPicker”文件夹拖入项目中 只使用照片选择功能 导入头文件 "HXPhotoViewController.h" 选完照片/视频后自动布局功能 导入头文件 "HXPhotoView.h" 二. 例子 Demo1 // 懒加载 照片管理类 - (HXPhotoManager *)manager { if (!_manager) { _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo]; } return _manager; } // 照片选择控制器 HXPhotoViewController *vc = [[HXPhotoViewController alloc] init]; vc.delegate = self; vc.manager = self.manager; [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil]; // 通过 HXPhotoViewControllerDelegate 代理返回选择的图片以及视频 - (void)photoViewControllerDidNext:(NSArray *)allList Photos:(NSArray *)photos Videos:(NSArray *)videos Original:(BOOL)original // 点击取消 - (void)photoViewControllerDidCancel Demo2 // 懒加载 照片管理类 - (HXPhotoManager *)manager { if (!_manager) { _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo]; } return _manager; } self.navigationController.navigationBar.translucent = NO; self.automaticallyAdjustsScrollViewInsets = YES; HXPhotoView *photoView = [[HXPhotoView alloc] initWithFrame:CGRectMake((414 - 375) / 2, 100, 375, 400) WithManager:self.manager]; photoView.delegate = self; photoView.backgroundColor = [UIColor whiteColor]; [self.view addSubview:photoView]; // 通过 HXPhotoViewDelegate 代理返回 选择、移动顺序、删除之后的图片以及视频 - (void)photoViewChangeComplete:(NSArray *)allList Photos:(NSArray *)photos Videos:(NSArray *)videos Original:(BOOL)isOriginal // 当 HXPhotoView 更新frame改变大小时 - (void)photoViewUpdateFrame:(CGRect)frame WithView:(UIView *)view 三. 更多 具体代码看请下载项目 发现的哪里有不好或不对的地方麻烦请联系我,大家一起讨论一起学习进步... QQ : 294005139
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值