Skip to content

Instantly share code, notes, and snippets.

@usagimaru
Created January 14, 2015 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usagimaru/c1c8c45c1a4e87eba488 to your computer and use it in GitHub Desktop.
Save usagimaru/c1c8c45c1a4e87eba488 to your computer and use it in GitHub Desktop.
Foundation/Core FoundationのToll-Free BridgingとARC

はじめに

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 オーナーシップを変更せずにキャスト

対応するヤツにキャスト

CFDictionaryRef cfdict = CFDictionaryCreate(kCFAllocatorDefault, NULL, NULL, 0, NULL, NULL);

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

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

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

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 が補完してくれるけど。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment