Do I need to manually release CFStringRef?

2019-07-07 03:18发布

Can you please tell me which is the right way and why in non ARC world.

+ (NSString *)getUUID {
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return [(NSString*) string autorelease];
}

or

+ (NSString *)getUUID {
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return (NSString*)string;
}

3条回答
女痞
2楼-- · 2019-07-07 03:26

The other answers are correct for manual retain counting. When you come to your senses ;^) and switch to ARC, you won't be able to send autorelease. Instead, under ARC, do it this way:

+ (NSString *)getUUID {
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return CFBridgingRelease(string);
}

A CFBridgingRelease is equivalent to a CFRelease for the purposes of balancing the +1 retain count returned by CFUUIDCreateString, but also returns a still-valid reference that ARC will take care of releasing.

查看更多
甜甜的少女心
3楼-- · 2019-07-07 03:43

Your method should return an autoreleased object so the client is responsible for obtaining ownership over the object, and it won't leak if they ignore the return value.

Number one is the correct method. The CFString is created, +1 retain count, autoreleased and returned for the client. The cast to NSString does not affect the retain count.

In the second method the CFString is created, +1 retain count, but never balanced with a release or autorelease.

查看更多
在下西门庆
4楼-- · 2019-07-07 03:44

CFStrings do need to be released. The first way is correct because CFString is toll-free bridged with NSString, and thus can safely be autoreleased like an NSString.

查看更多
登录 后发表回答