简体   繁体   中英

iPhone iOS createUUID leaking memory with ARC

I have a little method I found on the web that creates universally unique identifiers (UUID). The xCode static analyzer tells me that this method is leaking memory where it is marked in the code below.

Can someone tell me what's the correct way to write this code so there's no memory leak?

    +(NSString *)createUUID
    {

        // Create universally unique identifier (object)
        CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);

        // Get the string representation of CFUUID object.
//leak here
        NSString *uuidStr = (__bridge NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuidObject) ;

        CFRelease(uuidObject);

        return uuidStr;

    }

Try the following:

NSString *uuidStr = (__bridge_transfer NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuidObject);

You need to tell the NSString it is responsible for the ownership of the created CFString. This way, if you have ARC turned on, the CFString will be freed up automatically. If you use __bridge instead you will need to explicitly call CFRelease to release the CFString created by the *Create function call.

For more information about the __bridge casts read the Casting and Object Lifetime Semantics section of Apple's Core Foundation Design Concepts Guide.

Instead of __bridge :

NSString *uuidStr = (__bridge NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuidObject) ;

Use CFBridgingRelease . Your use of __bridge here is wrong. You are telling ARC that it has no memory management responsibilities with uuidStr . But it does have such responsibilities, because of the Create in the name of the function CFUUIDCreateString . ARC needs to add a release to correspond with the Create . Otherwise you will leak. You must tell ARC about this. CFBridgingRelease is the easiest way to do this.

For more, see the discussion in my book:

http://www.apeth.com/iOSBook/ch12.html#_memory_management_of_cftyperefs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM