你能告诉我哪种方法是正确的,为什么在非 ARC 世界中。
+ (NSString *)getUUID {
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return [(NSString*) string autorelease];
}
或者
+ (NSString *)getUUID {
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return (NSString*)string;
}
最佳答案
其他答案对于手动保留计数是正确的。当您恢复理智 ;^) 并切换到 ARC 时,您将无法发送 autorelease
。相反,在 ARC 下,这样做:
+ (NSString *)getUUID {
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return CFBridgingRelease(string);
}
为了平衡
CFBridgingRelease
返回的 +1 保留计数,CFRelease
等效于 CFUUIDCreateString
,但也会返回一个仍然有效的引用,ARC 将负责释放该引用。关于ios - 我需要手动释放 CFStringRef 吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17959760/