如何使用ARC在NSArray中存储CFUUIDRef对象?

时间:2011-12-15 00:12:06

标签: objective-c ios automatic-ref-counting

我和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,或者我是否已检索每个对象并自行CF发布它们?

2 个答案:

答案 0 :(得分:2)

我同意@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];

答案 1 :(得分:0)

在向阵列添加或删除CFUUIDRef时,您无需执行任何特殊操作,因为ARC会处理它。如果您可以访问2011 WWDC视频,则可以观看“部门中的Objective-C进展”。从分钟41:40开始,有一个关于ARC的CF Recipes的话题。使用__bridge和ARC时,不涉及CF内存管理,可能会保留并释放该值。

NSMutableArray *cfArray = [[NSMutableArray alloc] init];
CFUUIDRef uuid = CFUUIDCreate(NULL);
[cfArray addObject:(__bridge id)uuid];
id myStr = [cfArray objectAtIndex:0];
NSLog(@"My UUID:%@", myStr);
[cfArray removeObjectAtIndex:0];
NSLog(@"My UUID after remove from array:%@", myStr);
CFRelease(uuid);