Do I need to manually release CFStringRef?

半世苍凉 提交于 2019-12-10 18:52:43

问题


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;
}

回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/17959760/do-i-need-to-manually-release-cfstringref

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!