如何通过 Create/Get 的组合转让 Core Foundation 所有权?
How to transfer Core Foundation ownership with a mix of Create/Get?
在下面的代码中使用CFBridgingRelease
是否正确?
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
PopulateArray(&items);
CFDictionaryRef dict = CFArrayGetValueAtIndex(items, 0);
CFData data = CFDictionaryGetValue(dict, "key");
NSMutableArray* datas = [[NSMutableArray alloc] initWithObjects:CFBridgingRelease(data), nil];
return datas;
根据 Get Rule,我只是 data
所以我不拥有它,也不应该转让所有权。但我的推理是,最终 data
是 在 items
结构中创建的,我将它返回到一个数组中,所以我希望它作为参考-之后计算所以我应该转让所有权。
According to the Get Rule I'm just getting data so I don't own it, and shouldn't be transferring ownership.
正确,要转让所有权,您必须拥有所有权,而您没有。在没有所有权的情况下转让所有权很危险,预计会发生崩溃。
But my reasoning is that ultimately data is being created here inside the items structure, and I'm returning it in an array so I want it to be reference-counted afterwards so I should transfer ownership.
不,您所做的只是转移引用而没有所有权:
(__bridge NSData *)data
现在 ARC 将跟踪该表达式的结果。当您将生成的引用放在 NSMutableArray
中时,数组将取得所有权。此时您的数据至少有两个所有者,items
和 datas
。 ARC 管理 datas
及其引用的任何对象的生命周期,但是您必须在不再需要时自行释放 items
。如果不需要,可以在将数据放入 datas
后立即释放它。
HTH
在下面的代码中使用CFBridgingRelease
是否正确?
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
PopulateArray(&items);
CFDictionaryRef dict = CFArrayGetValueAtIndex(items, 0);
CFData data = CFDictionaryGetValue(dict, "key");
NSMutableArray* datas = [[NSMutableArray alloc] initWithObjects:CFBridgingRelease(data), nil];
return datas;
根据 Get Rule,我只是 data
所以我不拥有它,也不应该转让所有权。但我的推理是,最终 data
是 在 items
结构中创建的,我将它返回到一个数组中,所以我希望它作为参考-之后计算所以我应该转让所有权。
According to the Get Rule I'm just getting data so I don't own it, and shouldn't be transferring ownership.
正确,要转让所有权,您必须拥有所有权,而您没有。在没有所有权的情况下转让所有权很危险,预计会发生崩溃。
But my reasoning is that ultimately data is being created here inside the items structure, and I'm returning it in an array so I want it to be reference-counted afterwards so I should transfer ownership.
不,您所做的只是转移引用而没有所有权:
(__bridge NSData *)data
现在 ARC 将跟踪该表达式的结果。当您将生成的引用放在 NSMutableArray
中时,数组将取得所有权。此时您的数据至少有两个所有者,items
和 datas
。 ARC 管理 datas
及其引用的任何对象的生命周期,但是您必须在不再需要时自行释放 items
。如果不需要,可以在将数据放入 datas
后立即释放它。
HTH