本文介绍了NSMakeCollectable和ARC不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将旧项目转换为ARC。我有一个创建UUID的函数,但显然在使用ARC时不再支持:

I'm trying to convert my old project to ARC. I have a function which creates UUIDs, but apparently this is no longer supported when using ARC:

NSString *uuid = nil;
    CFUUIDRef theUUID = CFUUIDCreate(kCFAllocatorDefault);
    if (theUUID) {
        uuid = NSMakeCollectable(CFUUIDCreateString(kCFAllocatorDefault, theUUID));
        //[uuid autorelease];
        CFRelease(theUUID);
    }

我收到编译器错误(尝试转换时):'NSMakeCollectable'是不可用:在自动引用计数模式下不可用。

I get the compiler error (when trying to convert): 'NSMakeCollectable' is unavailable: not available in automatic reference counting mode.

所以我的问题是:如何在使用ARC时创建UUID?还有其他方法我现在应该使用吗?

So my question is: how do I create UUIDs when using ARC? Is there another way which I should now use?

推荐答案

NSMakeCollectable()是为了(基本上已弃用)Objective-C垃圾收集器的好处。 ARC对此一无所知。

NSMakeCollectable() is for the benefit of the (essentially deprecated) Objective-C garbage collector. ARC knows nothing about it.

您必须使用特殊的cast属性,通常是 __ bridge_transfer ,以确保内存没有泄露。 __ bridge_transfer 的使用如下:

You must use a special casting attribute, usually __bridge_transfer, to ensure that the memory is not leaked. __bridge_transfer is used like so:

id MakeUUID(void) {
    id result = nil;
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    if (uuid) {
        result = (__bridge_transfer id)uuid; // this "transfers" a retain from CF's control to ARC's control.
    }
    return result;
}

编辑:正如其他答案所述, CFBridgingRelease()为你做这件事。因此,代替使用(__ bridge_transfer id)uuid ,编写 CFBridgingRelease(uuid)可能更清晰。它们是等价的,所以你可以找到更具可读性的东西。

Edit: As other answers have mentioned, CFBridgingRelease() does this for you. So instead of using (__bridge_transfer id)uuid, it may be cleaner to write CFBridgingRelease(uuid). They are equivalent though, so it's up to you which you find more readable.

这篇关于NSMakeCollectable和ARC不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:50