gpt4 book ai didi

ios - block 中的 NSMutableArray addObject 给出空数组

转载 作者:行者123 更新时间:2023-11-29 02:26:55 24 4
gpt4 key购买 nike

我有一组列表 ALAsset URL。我想将该 URL 逐一转换为 ALAsset 并将其添加到新数组中。

这是我的代码:

-(void)retrieveAssetsWithArray:(NSArray *)assetsArray
{

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Background work
__block NSMutableArray *retrievedAssetsArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [assetsArray count]; i++)
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:[NSURL URLWithString:[assetsArray objectAtIndex:i]]
resultBlock:^(ALAsset *asset)
{
if (asset)
{
NSLog(@"assetss: %@", asset);
[retrievedAssetsArray addObject:asset];
NSLog(@"assets arayyyy: %@", retrievedAssetsArray);
}
}
failureBlock:^(NSError *error)
{
NSLog(@"Error: Cannot load asset - %@", [error localizedDescription]);
}
];
}

dispatch_async(dispatch_get_main_queue(), ^{
// Update UI
if ([self.delegate respondsToSelector:@selector(getRetrievedAssetsFromPhotoLibrary:)])
{
NSLog(@"retrievedAssetsArray :%@", retrievedAssetsArray);
[self.delegate getRetrievedAssetsFromPhotoLibrary:retrievedAssetsArray];
}
});
});
}

将 URL 转换为 ALAsset 的部分工作正常。但是retrievedAssetsArray当我尝试将其记录在 dispatch_async(dispatch_get_main_queue() 中时,返回如下:

retrievedAssetsArray :(
"ALAsset - Type:Unknown, URLs:(null)",
"ALAsset - Type:Unknown, URLs:(null)",
"ALAsset - Type:Unknown, URLs:(null)",
"ALAsset - Type:Unknown, URLs:(null)"
)

为什么会发生这种情况?谁能告诉我如何解决这个问题?干杯。

最佳答案

我找到了问题的答案:

-(void)retrieveAssetsWithArray:(NSArray *)assetsArray
{
__block NSMutableArray *retrievedAssetsArray = [[NSMutableArray alloc] init];
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

for (NSString *string in assetsArray) {
dispatch_async(queue, ^{
[library assetForURL:[NSURL URLWithString:string] resultBlock:^(ALAsset *asset) {
[retrievedAssetsArray addObject:asset];
dispatch_semaphore_signal(sema);
} failureBlock:^(NSError *error) {
dispatch_semaphore_signal(sema);
}];
});

dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

dispatch_release(sema);

/* Check out ALAssets and return in delegate methods*/
dispatch_async(dispatch_get_main_queue(), ^{
// Update UI
if ([self.delegate respondsToSelector:@selector(getRetrievedAssetsFromPhotoLibrary:)])
{
NSLog(@"retrieve %@", retrievedAssetsArray);
[self.delegate getRetrievedAssetsFromPhotoLibrary:retrievedAssetsArray];
}
});

}

关于ios - block 中的 NSMutableArray addObject 给出空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27401079/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com