iOS:方法返回块内布尔变量集的错误值



我有一个返回布尔值的方法。如果从URL中至少找到一个图像/资产,则应返回true。代码如下所示。在块内部,当我打印数组中对象的计数时,它会正确打印。但是,在块之外,计数为零,并且不进入if块,并且该方法始终返回FALSE。我想发生这种情况是因为函数在执行块之前返回。我该如何解决这个问题?如果块内的self.imageURL中至少添加了一个URL,我如何确保该方法返回true?

-(BOOL)getPhotos
{
self.imagesFound = FALSE;
//get all image url's from database
//for each row returned do the following:
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *URLString = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
NSURL *imageURL = [NSURL URLWithString:URLString];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:imageURL resultBlock:^(ALAsset *asset)
{
if (asset) {
//if an image exists with this URL, add it to self.imageURLs
[self.imageURLs addObject:URLString];
NSLog(@"no. of objects in array: %lu", (unsigned long)self.imageURLs.count);
}
}
failureBlock:^(NSError *error)
{
// error handling
NSLog(@"failure-----");
}];       
}                      
if (self.imageURLs.count > 0) {
NSLog(@"self.imageURLs count = %lu", (unsigned long)self.imageURLs.count);
self.imagesFound = TRUE;
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Sorry!" message:@"No photos found" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
return self.imagesFound;
}

这可能是因为块有时是异步的,即在执行之后

[library assetForURL:imageURL resultBlock:^(ALAsset *asset).....

它不会等待完成块的执行,它会立即执行下一个语句。

检查哪个日志正在打印第一个

NSLog(@"no. of objects in array: %lu", (unsigned long)self.imageURLs.count);

或之后的日志

[library assetForURL:imageURL resultBlock:^(ALAsset *asset).....
因此,块可以维护一组可以使用的状态(数据)以在执行时影响行为。

在块执行完成后编写所有代码,并发送通知而不是返回值。

[library assetForURL:imageURL resultBlock:^(ALAsset *asset)
{
if (asset) 
{
//if an image exists with this URL, add it to self.imageURLs
[self.imageURLs addObject:URLString];
self.imagesFound = TRUE;
//send a notificaton from here as TRUE,
}
}failureBlock:^(NSError *error)
{
//self.imagesFound = NO;
//display error alert.
//send a notificaton from here as FALSE,
}];   

这类事情几乎正是块上的委托或完成处理程序所要做的。因为您的块是异步的,所以在设置布尔值之前,它会继续并执行代码的其余部分。

要通过授权进行,您需要:

  1. 创建一个类,该类在实例化时在后台线程上执行您希望它执行的操作,并将调用方设置为委托。

  2. 完成后,回调委托方法,然后从那里相应地执行脚本。

OR只需添加一个完成处理程序,它将启动依赖于当前根本没有得到的结果的代码的其余部分。

根据我的经验,尽管委托需要更长的时间来编写,而且如果你是新手,你很难理解,但它使你的代码更加可重用,并且更好地抽象,以便能够在应用程序中需要相同异步计数或操作的其他地方重用。

最新更新