我对ARC感到困惑。我可以创建CFUUIDRef,也可以通过CFRetain和CFRelease管理引用计数。如何将它们添加到NSArray并将所有权传递给它?
CFUUIDRef *uuid = ...;
[arr setObject:myobj forKey:(__bridge id)uuid];
[arr removeObjectForKey:(__bridge id)uuid];
id myobj = [arr objectForKey:(__bridge id)uuid];
以上是设置,删除和检索的正确方法吗?如果我从该数组中删除一个条目,CFUUIDRef是否会自动释放,或者我是否已检索每个对象并自己将其CFRelease删除?
最佳答案
我同意@Ken Wong的回答,但我认为您应该使用(__bridge_transfer id)
,因为您要将CFUUIDRef
的所有权转让给数组。从数组中删除对象或将数组释放后,该对象将自动释放(但不必释放)。
NSMutableArray *array = /* assume this exists */;
CFUUIDRef uuid = /* assume this exists */;
[array addObject: (__bridge_tranfer id) uuid];
NSLog(@"Before = %@", uuid);
CFRelease(uuid);
// The CFUUIDRef "lives on" in the array
uuid = (__bridge CFUUIDRef) [array lastObject];
NSLog(@"After = %@", uuid);
// The UUID is deallocated (`uuid` is now an invalid reference)
[array release];
关于objective-c - 如何在带有ARC的NSArray中存储CFUUIDRef对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8513541/