13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Foundation/Core FoundationのToll-Free BridgingとARC

Posted at

忘れるのでメモ。

はじめに

ARC環境下ではFoundationオブジェクトとCore Foundationオブジェクトのキャストによる変換はいろいろと面倒になっているので要注意。

基本的に、

  • Foundation (NS):ARCの管理対象
  • Core Foundation (CF):MRC

使用する属性

__bridge_transfer CFBridgingRelease()
CFポインタ→ObjCポインタ、オーナーシップをMRCからARCへ変更
…CF→NSのときに使う

__bridge_retained CFBridgingRetain()
ObjCポインタ→CFポインタ、オーナーシップをARCからMRCへ変更
…NS→CFのときに使う

__bridge
オーナーシップを変更せずにキャスト

対応するヤツにキャスト

CF→NS@ARC
CFDictionaryRef cfdict = CFDictionaryCreate(kCFAllocatorDefault, NULL, NULL, 0, NULL, NULL);

// どちらでも良い
NSDictionary *nsdict1 = (__bridge_transfer NSDictionary*)cfdict;
NSDictionary *nsdict2 = (NSDictionary*)CFBridgingRelease(cfdict);
NS@ARC→CF
// どちらでも良い
CFDictionaryRef *cfdict1 = (__bridge_retained CFDictionaryRef)@{};
CFDictionaryRef *cfdict2 = (CFDictionaryRef)CFBridgingRetain(@{});

// CF は解放
CFRelease(cfdict1);
CFRelease(cfdict2);

配列とかに含める予定の NSString 等

NSString@ARC
NSString *nskey = @"Which";
NSString *nsstr = @"Cocoa !";

CFMutableDictionaryRef cfdict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, NULL);

// ARC なので __bridge でそのまま
CFDictionaryAddValue(cfdict, (__bridge CFStringRef)nskey), (__bridge CFStringRef)nsstr);

// CF は解放
CFRelease(cfdict);

明らかにキャストがおかしい場合は Xcode が補完してくれるけど。


間違いがあればご指摘ください。

13
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?