Skip to content

Instantly share code, notes, and snippets.

@satoshin2071
Created November 27, 2014 08:20
Show Gist options
  • Save satoshin2071/249d42fc563ce98b410b to your computer and use it in GitHub Desktop.
Save satoshin2071/249d42fc563ce98b410b to your computer and use it in GitHub Desktop.
#CoreFoundation入門 基本クラス その2

#CoreFoundation入門 基本クラス その2

概要

一回目の続き

CFData

bytebufferを扱う(ラッパー)クラス。NSDataとToll-free bridgingが可能

int main(int argc, const char * argv[]) {

    const UInt8 bytes[] = {0,1,2,3,4};
    CFDataRef data = CFDataCreate(kCFAllocatorDefault, bytes, 5);
    CFShow(data);
    CFRelease(data);
    
    CFShow(CFSTR("\n"));
    
    UInt8 *bytes2 = malloc(sizeof(UInt8) *10 );
    memset(bytes2, 1, sizeof(UInt8) * 10);
    CFDataRef data2 = CFDataCreate(kCFAllocatorDefault, bytes2, 10);
    
    // CFDataCreate時にコピーされているのでここでfree
    free(bytes2);
    CFShow(data2);
    CFRelease(data2);
    
    CFShow(CFSTR("\n"));
    
    return 0;
}

// 実行結果

<CFData 0x100208f10 [0x7fff7312af00]>{length = 5, capacity = 5, bytes = 0x0001020304}

<CFData 0x100208f10 [0x7fff7312af00]>{length = 10, capacity = 10, bytes = 0x01010101010101010101}

CFDictionary

ハッシュを管理するクラス。順番の概念は無いNSDictionaryとToll-free bridging可能.

int main(int argc, const char * argv[]) {

    const CFTypeRef keys[] = {CFSTR("key0"),CFSTR("key1")};
    const CFTypeRef values[] = {CFSTR("value0"),CFSTR("value1")};
    
    CFDictionaryRef dictionary;
    dictionary = CFDictionaryCreate(kCFAllocatorDefault, (const void**)keys,(const void**)values, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFShow(dictionary);
    CFRelease(dictionary);
    return 0;
}

// 実行結果
<CFBasicHash 0x100301c00 [0x7fff7312af00]>{type = immutable dict, count = 2,
entries =>
	0 : <CFString 0x100001080 [0x7fff7312af00]>{contents = "key1"} = <CFString 0x1000010c0 [0x7fff7312af00]>{contents = "value1"}
	1 : <CFString 0x100001060 [0x7fff7312af00]>{contents = "key0"} = <CFString 0x1000010a0 [0x7fff7312af00]>{contents = "value0"}
}

実行結果をみると順番の概念がないのがわかる。

CFDate

日付を扱うクラス。NSDateとToll-free bridging可能.

CFDateCreateのドキュメントを確認

CFDateRef CFDateCreate(CFAllocatorRef allocator, CFAbsoluteTime at);

第二引数にはCFAbsoluteTimeを渡すのがわかるが、CFAbsoluteTimeとは?ドキュメントを確認。

Absolute time is measured in seconds relative to the absolute reference date of Jan 1 2001 00:00:00 GMT.

2001/1/1 00:00:00からの相対秒

といわけで実際につくってみる。

int main(int argc, const char * argv[]) {

    CFAbsoluteTime time = CFAbsoluteTimeGetCurrent();
    printf("time = %f\n",time);
    
    CFDateRef date = CFDateCreate(kCFAllocatorDefault, time);
    CFShow(date);
    
    time = CFDateGetAbsoluteTime(date);
    printf("time = %f\n",time);
    
    CFRelease(date);
    return 0;
}

// 実行結果
time = 438767039.394114
2014-11-27 07:43:59 +0000
time = 438767039.394114

※2001年はじまりなのでUnixTimeではない点に注意

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