gpt4 book ai didi

ios - 避免像在 FMDatabaseQueue 中那样使用带有 block 方法的 __block 变量保留计数

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

我正在使用 FMDatabaseQueue,我不想使用 __block 变量保留计数,因为我有一个带有返回值的方法,这是读取数据库的结果,这是一个例子:

- (BOOL)existProduct:(int)id_product
{
__block BOOL exist = NO;

[self.dbQueue inDatabase:^(FMDatabase *db) {

FMResultSet *pr_query = [db executeQuery:@"SELECT id FROM product WHERE id_product = ?",[NSNumber numberWithInt:id_product]];

while ([pr_query next]) {

exist = YES;
}
}];

return exist;
}

文档是这样说的:

As described, instead, you can use a __block qualifier and set the myController variable to nil in the completion handler

MyViewController * __block myController = [[MyViewController alloc] init…];
// ...
myController.completionHandler = ^(NSInteger result) {
[myController dismissViewControllerAnimated:YES completion:nil];
myController = nil;
};

但是我不能放 exist = nil,因为它是我的返回值,所以我该如何解决这个问题?

编辑:在某些情况下,我有对象而不是原始变量来返回这样的值:

- (Product *)searchProduct:(int)id_product
{
__block Product *prod = nil;

[self.dbQueue inDatabase:^(FMDatabase *db) {

FMResultSet *pr_query = [db executeQuery:@"SELECT * FROM product WHERE id_product = ?",[NSNumber numberWithInt:id_product]];

while ([pr_query next]) {

prod = [[Product alloc] init]
prod.id = ...
...
}
}];

return prod;
}

最佳答案

问题是什么? exists 是原始类型 (BOOL)。原始类型不会被保留、释放或释放。

您的第一个代码块按原样没问题。

尽管您可以将 while 更改为 if,因为您只想知道是否有任何数据。无需迭代所有结果。

关于ios - 避免像在 FMDatabaseQueue 中那样使用带有 block 方法的 __block 变量保留计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27757237/

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