obsidian/笔记文件/2.笔记/__bridge_retained.md
2025-03-26 00:02:56 +08:00

26 lines
1.4 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#ios
`__bridge_retained`是 Objective-C 中的一个关键字,您在使用 Core Foundation 类型和自动引用计数 (ARC) 时会用到它。它表示您正在将 Core Foundation 对象的所有权转让给 ARC这意味着 ARC 现在将管理此对象的内存。
### 用法
当您使用 时`__bridge_retained`,实际上是告诉 ARC 接管 Core Foundation 对象的管理,这意味着当 Objective-C 对象超出范围时,它会自动释放它。这在将 Core Foundation 对象转换为其 Objective-C 对应对象时非常有用。
### 例子
以下是如何使用的示例`__bridge_retained`
``` objc
CFStringRef cfString = CFStringCreateWithCString(kCFAllocatorDefault, "Hello, Core Foundation!", kCFStringEncodingUTF8);
// Transfer ownership to ARC
NSString *objcString = (__bridge_retained NSString *)cfString;
// Now objcString is managed by ARC
// When objcString is released, the memory for the Core Foundation object will be released too
```
### 重要说明
- **内存管理**`__bridge_retained`:当您确定要创建 Core Foundation 对象并且希望 ARC 负责它时,使用至关重要。如果您在必要时未能使用它,最终可能会因过早释放而导致内存泄漏或崩溃。
- **谨慎使用**:使用时请注意所有权规则`__bridge_retained`。如果在 ARC 已管理的对象上调用它,则可能导致双重释放等问题。