gpt4 book ai didi

objective-c - NSString 到 CFStringRef 和 CFStringRef 到 ARC 中的 NSString?

转载 作者:IT老高 更新时间:2023-10-28 11:23:19 26 4
gpt4 key购买 nike

我想了解从 ARC 中的 CFStringRef 获取 NSString 的正确方法?反方向也一样,ARC中的CFStringRefNSString

在不造成内存泄漏的情况下,正确的方法是什么?

最佳答案

通常

NSString *yourFriendlyNSString = (__bridge NSString *)yourFriendlyCFString;

CFStringRef yourFriendlyCFString = (__bridge CFStringRef)yourFriendlyNSString;

现在,如果你想知道为什么会有 __bridge 关键字,你可以引用 Apple documentation .在那里你会发现:

__bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.

__bridge_retained or CFBridgingRetain casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to you. You are responsible for calling CFRelease or a related function to relinquish ownership of the object.

__bridge_transfer or CFBridgingRelease moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC. ARC is responsible for relinquishing ownership of the object.

这意味着在上述情况下,您正在转换对象而不更改所有权。这意味着在这两种情况下,您都将负责处理字符串的内存。

也有可能出于某种原因您想要转让所有权。

例如考虑以下代码段

- (void)sayHi {
CFStringRef str = CFStringCreateWithCString(NULL, "Hello World!", kCFStringEncodingMacRoman);

NSString * aNSString = (__bridge NSString *)str;

NSLog(@"%@", aNSString);

CFRelease(str); //you have to release the string because you created it with a 'Create' CF function
}

在这种情况下,您可能希望在转换时通过转移所有权来保存 CFRelease

- (void)sayHi {
CFStringRef str = CFStringCreateWithCString(NULL, "Hello World!", kCFStringEncodingMacRoman);

NSString * aNSString = (__bridge_transfer NSString *)str;
// or alternatively
NSString * aNSString = (NSString *)CFBridgingRelease(str);

NSLog(@"%@", aNSString);
}

str 的所有权已经转移,所以现在 ARC 将启动并为您释放内存。

另一方面,您可以使用 __bridge_retained 转换将 NSString * 转换为 CFString,这样您就可以拥有该对象您必须使用 CFRelease 显式释放它。


你可以把它包起来

NSString → CFString

// Don't transfer ownership. You won't have to call `CFRelease`
CFStringRef str = (__bridge CFStringRef)string;

// Transfer ownership (i.e. get ARC out of the way). The object is now yours and you must call `CFRelease` when you're done with it
CFStringRef str = (__bridge_retained CFStringRef)string // you will have to call `CFRelease`

CFString → NSString

// Don't transfer ownership. ARC stays out of the way, and you must call `CFRelease` on `str` if appropriate (depending on how the `CFString` was created)
NSString *string = (__bridge NSString *)str;

// Transfer ownership to ARC. ARC kicks in and it's now in charge of releasing the string object. You won't have to explicitly call `CFRelease` on `str`
NSString *string = (__bridge_transfer NSString *)str;

关于objective-c - NSString 到 CFStringRef 和 CFStringRef 到 ARC 中的 NSString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17227348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com