<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>cocoa*life</title>
	<atom:link href="http://www.cocoalife.net/feed" rel="self" type="application/rss+xml" />
	<link>http://www.cocoalife.net</link>
	<description>Whether we can achieve something entirely depends upon our intensity of faith.</description>
	<lastBuildDate>Thu, 04 Mar 2010 11:15:17 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>UITextFieldに入力されている文字数を動的に、非同期に数える。</title>
		<link>http://www.cocoalife.net/2010/03/post_546.html</link>
		<comments>http://www.cocoalife.net/2010/03/post_546.html#comments</comments>
		<pubDate>Wed, 03 Mar 2010 02:17:12 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Cocoa]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=546</guid>
		<description><![CDATA[				以下はUITextFieldに入力されている文字数を動的に、非同期に数える。 &#124; アクトインディ技術部隊報告書と同じものです。
				とあるUITextFieldによる入力フォームと、UIBarButtonItemによる「完了」ボタンがある画面を考えます。
				今回のエントリの目的はUITextFieldに文字が入力されていない、つまり空であるときは、「完了」ボタンを表示しない画面を作成するということです。
				ポイントはUIControlEventEditingChangedイベントを使うこと。
				最初はUITextFieldDelegateのtextField:shouldChangeCharactersInRange:replacementString:とかを使用することを考えましたが、文字を消去したときにボタンが消えない等々うまくいきませんでした。
				サンプルコードを書いてみます。
				- (void)setupUserInterface
{
    UIView      *contentView;
    UITextField *textField;

    contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self setView:contentView];
    [contentView release];

    doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
         [...]]]></description>
			<content:encoded><![CDATA[				<p>以下は<a target="_blank" href="http://tech.actindi.net/3476570782">UITextFieldに入力されている文字数を動的に、非同期に数える。 | アクトインディ技術部隊報告書</a>と同じものです。</p>
				<p>とあるUITextFieldによる入力フォームと、UIBarButtonItemによる「完了」ボタンがある画面を考えます。</p>
				<p>今回のエントリの目的はUITextFieldに文字が入力されていない、つまり空であるときは、「完了」ボタンを表示しない画面を作成するということです。</p>
				<p>ポイントはUIControlEventEditingChangedイベントを使うこと。<br />
				最初はUITextFieldDelegateのtextField:shouldChangeCharactersInRange:replacementString:とかを使用することを考えましたが、文字を消去したときにボタンが消えない等々うまくいきませんでした。</p>
				<p>サンプルコードを書いてみます。</p>
				<pre class="brush: objc;">- (void)setupUserInterface
{
    UIView      *contentView;
    UITextField *textField;

    contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self setView:contentView];
    [contentView release];

    doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                               target:self
                                                               action:@selector(respondsToDoneButtonTouchDown:)];

    textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    [contentView addSubview:textField];
    [textField release];
    [textField addTarget:self
                  action:@selector(respondsToEditingChanged:)
        forControlEvents:UIControlEventEditingChanged];
}

- (void)respondsToEditingChanged:(id)sender
{
    if ([sender isKindOfClass:[UITextField class]])
    {
        // 本当はsenderを用いずにメンバ変数とかにしておけばいいのだけれど、今回はあえて型変換をしてみる。
        if ([[(UITextField *)sender text] length])
        {
            [[self navigationItem] setRightBarButtonItem:doneButton animated:YES];
        }
        else
        {
            [[self navigationItem] setRightBarButtonItem:nil animated:YES];
        }
    }
}</pre>
				<p>参考<br />
				<a target="_blank" href="http://groups.google.co.jp/group/iphonesdkdevelopment/browse_thread/thread/0cc9032a397a02ff">Disable button if textField is empty &#8211; iPhone SDK Development</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/03/post_546.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>iPhoneによる位置情報関係のまとめ</title>
		<link>http://www.cocoalife.net/2010/01/post_498.html</link>
		<comments>http://www.cocoalife.net/2010/01/post_498.html#comments</comments>
		<pubDate>Sun, 31 Jan 2010 14:48:53 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Cocoa]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=498</guid>
		<description><![CDATA[				以下はiPhoneによる位置情報関係のまとめ &#124; アクトインディ技術部隊報告書と同様のものです。
				今回も前回のGeohashに引き続き、位置情報に関する内容です。
				ググれば出てくる内容なので、新しいことはなんにもないのが申し訳ないところです。
				位置情報に関するライブラリは
				
				CoreLocation
				MapKit
				
				などがあります。
				GPSで現在位置を取得するにはCoreLocationを使用し、地図を表示したり現在地の大まかな住所を取得するためにはMapKitを使用します。
				GPSで現在位置を取得するには
				CoreLocationではCLLocationManagerDelegateを実装し
				
- (void)setup
{
    CLLocationManager *locationManager = [[CLLocationManager alloc] init];
    if ([locationManager locationServicesEnabled])
    {
        [locationManager setDelegate:self];
        [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        [locationManager setDistanceFilter:kCLDistanceFilterNone];
    }
}

- (void)locationManager:(CLLocationManager [...]]]></description>
			<content:encoded><![CDATA[				<p>以下は<a target="_blank" href="http://tech.actindi.net/3473583175">iPhoneによる位置情報関係のまとめ | アクトインディ技術部隊報告書</a>と同様のものです。</p>
				<p>今回も前回のGeohashに引き続き、位置情報に関する内容です。<br />
				ググれば出てくる内容なので、新しいことはなんにもないのが申し訳ないところです。</p>
				<p>位置情報に関するライブラリは</p>
				<ul>
				<li>CoreLocation</li>
				<li>MapKit</li>
				</ul>
				<p>などがあります。</p>
				<p>GPSで現在位置を取得するにはCoreLocationを使用し、地図を表示したり現在地の大まかな住所を取得するためにはMapKitを使用します。</p>
				<h2>GPSで現在位置を取得するには</h2>
				<p>CoreLocationではCLLocationManagerDelegateを実装し</p>
				<pre class="brush: objc;">
- (void)setup
{
    CLLocationManager *locationManager = [[CLLocationManager alloc] init];
    if ([locationManager locationServicesEnabled])
    {
        [locationManager setDelegate:self];
        [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        [locationManager setDistanceFilter:kCLDistanceFilterNone];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@&quot;%@&quot;, newLocation);
}
</pre>
				<p>このようにすればLogに現在地の情報が取得できます。</p>
				<h2>地図を表示するには</h2>
				<pre class="brush: objc;">
- (void)setup
{
    CGRect screen = [[UIScreen mainScreen] bounds];
    MKMapView *mapView = [[MKMapView alloc] initWithFrame:screen];
    [[self view] addSubview:mapView];
    [mapView release];

    MKCoordinateRegion  region;
    region.center = [location coordinate];
    region.span.latitudeDelta = 0.005;
    region.span.longitudeDelta = 0.005;
    [mapView setRegion:region animated:YES];
}
</pre>
				<p>とすれば、locationで指定した座標に移動します。</p>
				<h2>現在地を取得するには</h2>
				<p>MKReverseGeocoderDelegateを実装し</p>
				<pre class="brush: objc;">
- (void)setup
{
    MKReverseGeocoder *reverseGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:[location coordinate]];
    [reverseGeocoder setDelegate:self];
    [reverseGeocoder start];
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
    NSLog(@&quot;%@&quot;, [placemark title]);
}
</pre>
				<p>とすることで取得することができます。<br />
				すべてのAPIが非常にシンプルに作られているので、使用するのは非常に簡単です。</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/01/post_498.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>コメントをDISQUSを使用したものに変更しました。</title>
		<link>http://www.cocoalife.net/2010/01/post_484.html</link>
		<comments>http://www.cocoalife.net/2010/01/post_484.html#comments</comments>
		<pubDate>Sun, 24 Jan 2010 04:13:46 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=484</guid>
		<description><![CDATA[				このblogのコメントをDisqusを使用したものに変更しました。
				既存のものはimportしました。
				手順としては
				
				WordPressのPluginであるDISQUS Comment Systemをダウンロードし、wp-contents/pluginsにインストール。
				WordPressの管理画面の&#8221;Settings&#8221; &#8211; &#8220;DISQUS&#8221;にゆく。
				&#8220;Import comments into Disqus&#8221;ボタンを押して既存のコメントをDisqusにインポートする（しばらくかかるのでしばし待つ）。
				
				多分これぐらいで、超簡単に導入することができました。
				てっきりコメントのインポートがかったるいものだと考えていたのですが、そんなことはなく、もっと早くやっておけばよかったと思いました。
]]></description>
			<content:encoded><![CDATA[				<p>このblogのコメントを<a target="_blank" href="http://disqus.com/">Disqus</a>を使用したものに変更しました。<br />
				既存のものはimportしました。</p>
				<p>手順としては</p>
				<ol>
				<li>WordPressのPluginである<a target="_blank" href="http://wordpress.org/extend/plugins/disqus-comment-system/">DISQUS Comment System</a>をダウンロードし、wp-contents/pluginsにインストール。</li>
				<li>WordPressの管理画面の&#8221;Settings&#8221; &#8211; &#8220;DISQUS&#8221;にゆく。</li>
				<li>&#8220;Import comments into Disqus&#8221;ボタンを押して既存のコメントをDisqusにインポートする（しばらくかかるのでしばし待つ）。</li>
				</ol>
				<p>多分これぐらいで、超簡単に導入することができました。<br />
				てっきりコメントのインポートがかったるいものだと考えていたのですが、そんなことはなく、もっと早くやっておけばよかったと思いました。</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/01/post_484.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Objective-C的？？？Geohash</title>
		<link>http://www.cocoalife.net/2010/01/post_485.html</link>
		<comments>http://www.cocoalife.net/2010/01/post_485.html#comments</comments>
		<pubDate>Sun, 24 Jan 2010 00:14:06 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Cocoa]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=485</guid>
		<description><![CDATA[				以下はObjective-C的？？？Geohash &#124; アクトインディ技術部隊報告書と同様のものです。
				先日chibaさんがGeohashをdecodeするものをCLで書いていらしたので、それを微妙に参考にしながらCocoaのCoreLocationのCLLocationにgeohashをencode/decodeするメソッド追加してみました。
				本当はビット演算がしたいのですが、文字列処理の方が自分には単純で簡単だったため、とりあえず今回は文字列処理にしてみました。
				我ながらひどいコードだと思いますので、これからリファクタリングをしていきたいところです。
				[CLLocation+Geohash.h]
				
#import &#60;CoreLocation/CoreLocation.h&#62;
#import &#60;Foundation/Foundation.h&#62;

@interface CLLocation(Geohash)

@property (nonatomic, readonly)   NSString    *geohash;

+ (CLLocation *)locationFromGeohash:(NSString *)aGeohash;

@end

				[CLLocation+Geohash.m]
				
#import &#34;CLLocation+Geohash.h&#34;

#include &#60;math.h&#62;

NSString *int_to_binary(NSUInteger input)
{
    if (input == 1 &#124;&#124; input == 0)
    {
        return [NSString stringWithFormat:@&#34;%d&#34;, input];
    }

    [...]]]></description>
			<content:encoded><![CDATA[				<p>以下は<a target="_blank" href="http://tech.actindi.net/3472988345">Objective-C的？？？Geohash | アクトインディ技術部隊報告書</a>と同様のものです。</p>
				<p>先日<a target="_blank" href="http://tech.actindi.net/3472464385">chibaさんがGeohashをdecodeするものをCLで書いていらした</a>ので、それを微妙に参考にしながらCocoaのCoreLocationのCLLocationにgeohashをencode/decodeするメソッド追加してみました。</p>
				<p>本当はビット演算がしたいのですが、文字列処理の方が自分には単純で簡単だったため、とりあえず今回は文字列処理にしてみました。</p>
				<p>我ながらひどいコードだと思いますので、これからリファクタリングをしていきたいところです。</p>
				<p>[CLLocation+Geohash.h]</p>
				<pre class="brush: objc;">
#import &lt;CoreLocation/CoreLocation.h&gt;
#import &lt;Foundation/Foundation.h&gt;

@interface CLLocation(Geohash)

@property (nonatomic, readonly)   NSString    *geohash;

+ (CLLocation *)locationFromGeohash:(NSString *)aGeohash;

@end
</pre>
				<p>[CLLocation+Geohash.m]</p>
				<pre class="brush: objc;">
#import &quot;CLLocation+Geohash.h&quot;

#include &lt;math.h&gt;

NSString *int_to_binary(NSUInteger input)
{
    if (input == 1 || input == 0)
    {
        return [NSString stringWithFormat:@&quot;%d&quot;, input];
    }

    return [NSString stringWithFormat:@&quot;%@%d&quot;, int_to_binary(input / 2), input % 2];
}

double parse_binary(NSString *binary, double max, double min)
{
    double mid = 0.0;

    for (NSUInteger i = 0; i &lt; [binary length]; ++i)
    {
        if ([binary characterAtIndex:i] == '1')
        {
            min = mid;
        }
        else
        {
            max = mid;
        }

        mid = (max + min) / 2;
    }

    return mid;
}

NSUInteger binary_to_int(NSString *input)
{
    NSUInteger result, length;

    result = 0;
    length = [input length];

    for (NSUInteger i = 0; i &lt; length; ++i)
    {
        if ([input characterAtIndex:i] == '1')
        {
            result += pow(2, length - i - 1);
        }
    }

    return result;
}

NSString * generate_binary(double input, double max, double min, int cutoff)
{
    NSMutableString     *result;
    double              mid;

    result = [NSMutableString string];
    for (int i = 0; i &lt; cutoff; ++i)
    {
        mid = (max + min) / 2;

        if (input &gt; mid)
        {
            [result appendString:@&quot;1&quot;];
            min = mid;
        }
        else
        {
            [result appendString:@&quot;0&quot;];
            max = mid;
        }
    }

    return [NSString stringWithString:result];
}

@implementation CLLocation(Geohash)

- (NSString *)geohash
{
    int cutoff = 15;
    NSString *base32_characters  = @&quot;0123456789bcdefghjkmnpqrstuvwxyz&quot;;

    NSString            *bin_lat, *bin_lng;
    NSMutableString     *bin_packed, *result;

    bin_lat = generate_binary([self coordinate].latitude, 90.0, -90.0, cutoff);
    bin_lng = generate_binary([self coordinate].longitude, 180.0, -180.0, cutoff);

    bin_packed = [NSMutableString string];

    for (int i = 0; i &lt; [bin_lat length]; ++i)
    {
        [bin_packed appendFormat:@&quot;%c%c&quot;, [bin_lng characterAtIndex:i], [bin_lat characterAtIndex:i]];
    }

    result = [NSMutableString string];

    // extract by 5-bit.
    for (int i = 0; i &lt; [bin_packed length] / 5; ++i)
    {
        NSUInteger index;
        index = binary_to_int([bin_packed substringWithRange:NSMakeRange(i * 5, 5)]);
        [result appendFormat:@&quot;%c&quot;, [base32_characters characterAtIndex:index]];
    }

    return result;
}

+ (CLLocation *)locationFromGeohash:(NSString *)aGeohash
{
    NSString *base32_characters  = @&quot;0123456789bcdefghjkmnpqrstuvwxyz&quot;;

    NSMutableString *bin_packed, *bin_lat, *bin_lng;

    bin_packed = [NSMutableString string];

    for (NSUInteger i = 0; i &lt; [aGeohash length]; ++i)
    {
        NSString *character;
        character = [[NSMutableString stringWithFormat:@&quot;%c&quot;, [aGeohash characterAtIndex:i]] lowercaseString];

        for (NSUInteger j = 0; j &lt; [base32_characters length]; ++j)
        {
            if ([character isEqualToString:[NSString stringWithFormat:@&quot;%c&quot;, [base32_characters characterAtIndex:j]]])
            {
                NSMutableString *binary;
                binary = [NSMutableString stringWithFormat:@&quot;%@&quot;, int_to_binary(j)];

                NSUInteger length = [binary length];
                for (NSUInteger k = 0; k &lt; 5 - length; ++k)
                {
                    [binary insertString:@&quot;0&quot; atIndex:0];
                }

                [bin_packed appendString:binary];
                break;
            }
        }
    }

    bin_lat = [NSMutableString string];
    bin_lng = [NSMutableString string];

    for (NSUInteger i = 0; i &lt; [bin_packed length]; ++i)
    {
        if (i % 2)
        {
            // a latitude is composed of odd bits.
            [bin_lat appendFormat:@&quot;%c&quot;, [bin_packed characterAtIndex:i]];
        }
        else
        {
            // a longitude is composed of even bits.
            [bin_lng appendFormat:@&quot;%c&quot;, [bin_packed characterAtIndex:i]];
        }
    }

    return [[CLLocation alloc] initWithLatitude:parse_binary(bin_lat, 90.0, -90.0)
                                      longitude:parse_binary(bin_lng, 180.0, -180.0)];
}

@end
</pre>
				<p>NSStringでかなり遅いcharacterAtIndexを使いまくっている。</p>
				<h2>参考</h2>
				<p><a href="http://en.wikipedia.org/wiki/Geohash">Geohash &#8211; Wikipedia, the free encyclopedia<br />
				<a target="_blank" href="http://d.hatena.ne.jp/yuroyoro/20100115/1263526125">GeoHashのdecodeのアルゴリズムの解説します &#038; ScalaのGeoHashライブラリを作ってみました(仮) &#8211; ゆろよろ日記</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/01/post_485.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Delaunay Tessellation for iPhone</title>
		<link>http://www.cocoalife.net/2010/01/post_842.html</link>
		<comments>http://www.cocoalife.net/2010/01/post_842.html#comments</comments>
		<pubDate>Wed, 13 Jan 2010 03:12:31 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Cocoa]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/2009/08/post_842.html</guid>
		<description><![CDATA[				以下の文章はDelaunay Tessellation for iPhone &#124; アクトインディ技術部隊報告書と同様のものです。
				プログラムプレゼンテーションの第2回は、iPhoneを用いてDelaunay分割をするというものにしてみました。
				本当は他のものをやるつもりだったのですが、前回のプログラムプレゼンテーションではkomagataさんがObjective-Cのキメラさ、カオスさをおもしろがっていたと勝手に仮定して、Objective-C++でさらなるカオスさを目指すことにしました。
				そんな折りに以前ドロネー分割をするためのプログラムをつくって、アップロードしようかなといっていたのを思い出しました。
				ということで、今回はそれを流用することにしました。
				単純に移植するだけだから簡単だろと思ったところ、意外と手直しに時間がかかってしまいました。
				ドロネー分割については計算幾何学で出てくるものですが、この余白はそれを書くのにはせますぎるということで、ググればきっとわかる！！！
				ソースコードはこちらです。
				ライブラリとしてBoost C++ Librariesを使用しています。
				実行すると、毎回ランダムな10点を作成し、下図のようにドロネー分割された図が表示されます。
				　　　
				右側の図は外接円も表示させた場合です。
				ドロネー分割では生成された三角形によって作られる外接円の中に、その三角形以外の点が含まれてはいけません。
				ランダムな点を生成する部分にはboost::randomを用い、ドロネー分割を計算する部分はC++で書かれています。
				Objective-CとC++のコードを混ぜる場合の注意点は、HMDTさんによくまとめられているのでこちらを参照していただくのがよいかと思います。
				HMDT &#8211; Objective-C++
				Objective-C++のソースを書かれるときは、.mとなっている拡張子を.mmにしてくださいね。
				自分はこれをしないでObjective-C++のファイルだと認識されずはまりまくりました。
				こんな風にC++のコードも簡単に使用することができるので、Objective-Cを使われている皆様もぜひ組み合わせてみてはいかがでしょうか？？？
				P.S.
				本当はNSOperationを使って、スレッドを新しく作ってバックグラウンドで処理をしたかったのですが、プログラムの構造上面倒なのでやめました。
				参考
				Objective-C プログラミング言語：C++ と Objective-C の併用
				HMDT &#8211; Objective-C++
]]></description>
			<content:encoded><![CDATA[				<p>以下の文章は<a target="_blank" href="http://tech.actindi.net/3472341020">Delaunay Tessellation for iPhone | アクトインディ技術部隊報告書</a>と同様のものです。</p>
				<p><a target="_blank" href="http://docs.komagata.org/4191">プログラムプレゼンテーション</a>の第2回は、iPhoneを用いてDelaunay分割をするというものにしてみました。</p>
				<p>本当は他のものをやるつもりだったのですが、<a target="_blank" href="http://www.cocoalife.net/2009/07/post_839.html">前回のプログラムプレゼンテーション</a>では<a target="_blank" href="http://www.komagata.org/">komagataさん</a>がObjective-Cのキメラさ、カオスさをおもしろがっていたと勝手に仮定して、Objective-C++でさらなるカオスさを目指すことにしました。</p>
				<p>そんな折りに<a target="_blank" href="http://www.cocoalife.net/2008/03/post_539.html">以前ドロネー分割をするためのプログラムをつくって、アップロードしようかなといっていた</a>のを思い出しました。</p>
				<p>ということで、今回はそれを流用することにしました。<br />
				単純に移植するだけだから簡単だろと思ったところ、意外と手直しに時間がかかってしまいました。</p>
				<p>ドロネー分割については計算幾何学で出てくるものですが、この余白はそれを書くのにはせますぎるということで、ググればきっとわかる！！！</p>
				<p><a target="_blank" href="http://bitbucket.org/milkcocoa/delaunay/">ソースコードはこちら</a>です。<br />
				ライブラリとして<a target="_blank" href="http://www.boost.org/">Boost C++ Libraries</a>を使用しています。</p>
				<p>実行すると、毎回ランダムな10点を作成し、下図のようにドロネー分割された図が表示されます。</p>
				<p><a href="http://www.cocoalife.net/wp-content/uploads/2010/01/1301.png"><img class="alignnone" title="Delaunay tessellation" src="http://www.cocoalife.net/wp-content/uploads/2010/01/1301.png" alt="Delaunay tessellation" width="240" /></a>　　　<a href="http://www.cocoalife.net/wp-content/uploads/2010/01/1302.png"><img class="alignnone" title="Delaunay tessellation with circumcircles" src="http://www.cocoalife.net/wp-content/uploads/2010/01/1302.png" alt="Delaunay tessellation with circumcircles" width="240" /></a></p>
				<p>右側の図は外接円も表示させた場合です。<br />
				ドロネー分割では生成された三角形によって作られる外接円の中に、その三角形以外の点が含まれてはいけません。</p>
				<p>ランダムな点を生成する部分にはboost::randomを用い、ドロネー分割を計算する部分はC++で書かれています。</p>
				<p>Objective-CとC++のコードを混ぜる場合の注意点は、HMDTさんによくまとめられているのでこちらを参照していただくのがよいかと思います。<br />
				<a target="_blank" href="http://homepage.mac.com/mkino2/spec/objectiveC++/objectiveC++.html">HMDT &#8211; Objective-C++</a></p>
				<p>Objective-C++のソースを書かれるときは、.mとなっている拡張子を.mmにしてくださいね。<br />
				自分はこれをしないでObjective-C++のファイルだと認識されずはまりまくりました。</p>
				<p>こんな風にC++のコードも簡単に使用することができるので、Objective-Cを使われている皆様もぜひ組み合わせてみてはいかがでしょうか？？？</p>
				<p>P.S.<br />
				本当はNSOperationを使って、スレッドを新しく作ってバックグラウンドで処理をしたかったのですが、プログラムの構造上面倒なのでやめました。</p>
				<p>参考<br />
				<a target="_blank" href="http://developer.apple.com/jp/documentation/Cocoa/Conceptual/ObjectiveC/3objc_language_overview/chapter_7_section_10.html">Objective-C プログラミング言語：C++ と Objective-C の併用</a><br />
				<a target="_blank" href="http://homepage.mac.com/mkino2/spec/objectiveC++/objectiveC++.html">HMDT &#8211; Objective-C++</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/01/post_842.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>複数行にわたったテキストを含むUILabelを適切な高さに調節する。</title>
		<link>http://www.cocoalife.net/2010/01/post_829.html</link>
		<comments>http://www.cocoalife.net/2010/01/post_829.html#comments</comments>
		<pubDate>Sat, 09 Jan 2010 14:13:12 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Cocoa]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=829</guid>
		<description><![CDATA[				複数行にわたったテキストを表示するためのUILabelのインスタンスであるlabelがあり、そのlabelを適切なサイズ高さに変更したい時がありました。
				
// すでに以下の2行は他の部分で設定されている。
[label setLineBreakMode:UILineBreakModeWordWrap];
[label setNumberOfLines:0];

CGRect *frame;

frame = [label frame];
frame.size = CGSizeMake(WIDTH, 0);

[label setFrame:frame];
[label setText:@&#34;long long long text...&#34;];
[label sizeToFit];

				ポイントはnumberOfLinesを0にすることと、sizeToFitメッセージを呼び出すこと。
				numberOfLinesを0にしないと、sizeToFitを呼び出した時点で、指定した幅が無視されてしまう気がする。
				毎回frameの幅を決めているのは、テキストが何度も書き換わる場所だから。
				テキストが短いものになった場合、sizeToFitメッセージで短い幅が設定されてしまうと以降ずっとその短い幅になったままになってしまうため。
				でもAppleのドキュメントには、以下のようにsizeToFitメッセージはnumberOfLinesを考慮するって書いてある。
				自分のやり方がおかしいのか？
				
				「UILabel Class Reference」より抜粋
				
				
				When the receiver is resized using the sizeToFit method, resizing takes into account the value stored in this property. For example, if this property is set to 3, the sizeToFit method resizes the receiver so that it [...]]]></description>
			<content:encoded><![CDATA[				<p>複数行にわたったテキストを表示するためのUILabelのインスタンスであるlabelがあり、そのlabelを適切なサイズ高さに変更したい時がありました。</p>
				<pre class="brush: objc;">
// すでに以下の2行は他の部分で設定されている。
[label setLineBreakMode:UILineBreakModeWordWrap];
[label setNumberOfLines:0];

CGRect *frame;

frame = [label frame];
frame.size = CGSizeMake(WIDTH, 0);

[label setFrame:frame];
[label setText:@&quot;long long long text...&quot;];
[label sizeToFit];
</pre>
				<p>ポイントはnumberOfLinesを0にすることと、sizeToFitメッセージを呼び出すこと。<br />
				numberOfLinesを0にしないと、sizeToFitを呼び出した時点で、指定した幅が無視されてしまう気がする。</p>
				<p>毎回frameの幅を決めているのは、テキストが何度も書き換わる場所だから。<br />
				テキストが短いものになった場合、sizeToFitメッセージで短い幅が設定されてしまうと以降ずっとその短い幅になったままになってしまうため。</p>
				<p>でもAppleのドキュメントには、以下のようにsizeToFitメッセージはnumberOfLinesを考慮するって書いてある。<br />
				自分のやり方がおかしいのか？</p>
				<dl class="quote">
				<dt>「<cite>UILabel Class Reference</cite>」より抜粋</dt>
				<dd>
				<blockquote>
				When the receiver is resized using the sizeToFit method, resizing takes into account the value stored in this property. For example, if this property is set to 3, the sizeToFit method resizes the receiver so that it is big enough to display three lines of text.</p></blockquote>
				</dd>
				<dt class="cite">
				引用元: <a href="http://developer.apple.com/iPhone/library/documentation/UIKit/Reference/UILabel_Class/Reference/UILabel.html">UILabel Class Reference</a>
				</dt>
				</dl>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/01/post_829.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RSpecでMacro？を書く。</title>
		<link>http://www.cocoalife.net/2010/01/post_846.html</link>
		<comments>http://www.cocoalife.net/2010/01/post_846.html#comments</comments>
		<pubDate>Fri, 08 Jan 2010 06:32:33 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=846</guid>
		<description><![CDATA[				RSpecを使ってSpecを書いていると何度も同じことを書くことが多いです。
				たとえばパラメータに応じてページタイトルを変えたい場合とか、validationがきちんと行われているかとか。。。
				毎回、 it &#8220;should have hoge&#8221; do &#8230; end と書いているのは大変です。
				RSpecではいくつかの方法を使用して、もっと簡単に書くことができます。
				クラスメソッドを使う
				一つのspecファイルで何度も使うものであればクラスメソッドにします。
				[$RAILS_ROOT/spec/views/articles/index.html.erb_spec.rb]
				
describe &#34;/articles&#34; do
  def self.it_should_have_tag(selector, content)
    it &#34;should have '#{content}' at '#{selector}'&#34; do
      response.should(have_tag(selector, content))
    end
  end
end

				と書いておけば、以下のような書き方が可能になります。
				[$RAILS_ROOT/spec/views/articles/index.html.erb_spec.rb]
				
describe &#34;/articles&#34; do
  def self.it_should_have_tag(selector, content)
    it &#34;should have '#{content}' at '#{selector}'&#34; do
  [...]]]></description>
			<content:encoded><![CDATA[				<p>RSpecを使ってSpecを書いていると何度も同じことを書くことが多いです。</p>
				<p>たとえばパラメータに応じてページタイトルを変えたい場合とか、validationがきちんと行われているかとか。。。<br />
				毎回、 it &#8220;should have hoge&#8221; do &#8230; end と書いているのは大変です。<br />
				RSpecではいくつかの方法を使用して、もっと簡単に書くことができます。</p>
				<h2>クラスメソッドを使う</h2>
				<p>一つのspecファイルで何度も使うものであればクラスメソッドにします。</p>
				<p>[$RAILS_ROOT/spec/views/articles/index.html.erb_spec.rb]</p>
				<pre class="brush: ruby;">
describe &quot;/articles&quot; do
  def self.it_should_have_tag(selector, content)
    it &quot;should have '#{content}' at '#{selector}'&quot; do
      response.should(have_tag(selector, content))
    end
  end
end
</pre>
				<p>と書いておけば、以下のような書き方が可能になります。</p>
				<p>[$RAILS_ROOT/spec/views/articles/index.html.erb_spec.rb]</p>
				<pre class="brush: ruby;">
describe &quot;/articles&quot; do
  def self.it_should_have_tag(selector, content)
    it &quot;should have '#{content}' at '#{selector}'&quot; do
      response.should(have_tag(selector, content))
    end
  end

  it_should_have_tag('tr&gt;td', 'MyString')
end
</pre>
				<p>it_should_have_tag(&#8217;tr>td&#8217;, &#8216;MyString&#8217;) の部分だけで適切なspecに展開されます。<br />
				1行で簡潔に書けますので、理解する時間も短くてすみます。</p>
				<p>自分はページタイトル、meta description、meta keywords、RSSのスペックに以下のコードを使用しています。</p>
				<p>[$RAILS_ROOT/spec/views/articles/index.html.erb_spec.rb]</p>
				<pre class="brush: ruby;">
describe &quot;/articles&quot; do
  def self.it_should_have_tag(selector, content)
    it &quot;should have '#{content}' at '#{selector}'&quot; do
      response.should(have_tag(selector, content))
    end
  end

  def self.it_should_have_page_title(title)
    it_should_have_tag('head&gt;title', title)
  end

  def self.it_should_have_meta_description(meta_description)
    it_should_have_tag('head&gt;meta[name=description][content=?]', meta_description)
  end

  def self.it_should_have_meta_keywords(meta_keywords)
    it_should_have_tag('head&gt;meta[name=keywords][content=?]', meta_keywords)
  end

  def self.it_should_have_rss_link(link)
    it_should_have_tag('head&gt;link[rel=alternate][type=application/rss+xml][href=?]', link)
  end
end
</pre>
				<h2>モジュールに追い出す</h2>
				<p>さらによく使う項目、上記のhtmlに関するspecなどはたくさんのところに書かれるであろうことが推測されます。<br />
				そういう場合には、モジュールに追い出してしまうということが可能だということを同僚の<a target="_blank" href="http://read-eval-print.blogspot.com/">quekさん</a>に教えていただきました。<sup>1</sup></p>
				<p>$RAILS_ROOT/spec/support フォルダにモジュールのファイルを書きます。<br />
				上記の例であれば</p>
				<p>[$RAILS_ROOT/spec/support/tag_macros.rb]</p>
				<pre class="brush: ruby;">
module TagMacros
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def it_should_have_tag(selector, content)
      it &quot;should have '#{content}' at '#{selector}'&quot; do
        response.should(have_tag(selector, content))
      end
    end

    def it_should_have_page_title(title)
      it_should_have_tag('head&gt;title', title)
    end

    def it_should_have_meta_description(meta_description)
      it_should_have_tag('head&gt;meta[name=description][content=?]', meta_description)
    end

    def it_should_have_meta_keywords(meta_keywords)
      it_should_have_tag('head&gt;meta[name=keywords][content=?]', meta_keywords)
    end

    def it_should_have_rss_link(link)
      it_should_have_tag('head&gt;link[rel=alternate][type=application/rss+xml][href=?]', link)
    end
  end
end
</pre>
				<p>使用する際には include TagMacros を書いておきます。</p>
				<p>[$RAILS_ROOT/spec/views/articles/index.html.erb_spec.rb]</p>
				<pre class="brush: ruby;">
describe &quot;/articles&quot; do
  include TagMacros

  it_should_have_tag('tr&gt;td', 'MyString')
end
</pre>
				<p>自分のような include 〜 を書くのもものぐさだという人は、 $RAILS_ROOT/spec/spec_helper.rb に config.include メソッドを使用すれば、自動的に読み込まれるようになります。</p>
				<p>[$RAILS_ROOT/spec/spec_helper.rb]</p>
				<pre class="brush: ruby;">
Spec::Runner.configure do |config|
  # ...
  config.include(TagMacros, :type =&gt; [:views])
  # ...
end
</pre>
				<p>上記のように :type を指定すれば view だけで読み込まれるというような指定も可能です。</p>
				<h2>参考</h2>
				<p><a target="_blank" href="http://railscasts.com/episodes/157-rspec-matchers-macros">Railscasts &#8211; RSpec Matchers &#038; Macros</a><br />
				<a target="_blank" href="http://www.benmabey.com/2008/06/08/writing-macros-in-rspec/">Writing Macros in RSpec • Blog Archive • Ben Mabey</a></p>
				<p>P.S.<br />
				参考にしたサイトではMacroと書いてありますが、どうもこれをMacroと読んでいいものなのかどうかかなり謎なので、タイトルはMacro？と？付きにしてみましたwww</p>
				<ol class="footnotes"><li id="footnote_0_846" class="footnote">quekさんによると、下の「参考」のところに書いた Railscasts に同様のことが書いてあり、そのアドレスを過去の自分は社内のチケットに書いていたらしいのですが、モジュールに出すことは全く知りませんでしたwww</li></ol>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/01/post_846.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>「カールじいさんの空飛ぶ家」を観ました。</title>
		<link>http://www.cocoalife.net/2009/12/post_848.html</link>
		<comments>http://www.cocoalife.net/2009/12/post_848.html#comments</comments>
		<pubDate>Sun, 06 Dec 2009 16:06:49 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Movie]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=848</guid>
		<description><![CDATA[				WALL-Eを観て、とても感激したのがもう1年近くも前になった（読み返してみましたが、なんだかずいぶんと稚拙な文章だなw）。
				cocoa*life &#8211; 「WALL-E」を観ました
				この映画はずっと以前からも生みたくてうずうずしていた。
				はやる気持ちを抑え、初日の初回に観てきた。
				WALL-Eを観たあのときも、とんでもない映画を観たなぁという思いがあったけれど、Pixarはそれを軽々と超えていったと思う。
				10月の終わりから11月の始めにかけて、これを書いているわずかひと月前、今まで生きてきた中で最低最悪で絶望的なことが起こり（それについては、来年のこの時期が来たら書くかもしれない）とても悲しみ、傷ついたから、余計映画の内容ともシンクロしてしまった。
				そのおかげか？途中で何度も何度も泣いた。
				それでもこのことを差し引いても、とてもとてもすてきな映画だった。
				冒頭の愛妻との愛情溢れる倖せな生活、そして死。
				言葉がないからなのか、心にすっとその倖せ、喜び、悲しみがしみいってくる。
				だからこそ、一見気むずかしそうに見えるカールじいさんが、どれだけの悲しみと後悔を携えて旅に出ようとしているのか観る人にはわかる。
				この映画の根底を流れる物語は「手放し」なのかもしれないと自分には映った。
				愛する妻にしてあげられなかった二人の夢を叶え、後悔を手放すための物語。
				これから大切にしてゆく周りの人たちを救うため、今まで頑なに拘っていたものを手放す物語。
				執着しすぎた故、ついに望みを叶えられなかった人の物語。
				手放そうとするとき、人はいろいろな感情を感じ、今まで自分には何が大切だったのか、これからの自分には何が大切なのかということが見えてくる。
				人間の儚さ、悲しさ。
				その一方で、愛そうとするときの強さ、優しさ、勇気。
				いろいろな感情をたった一つの映画で見せてくれた。
]]></description>
			<content:encoded><![CDATA[				<p>WALL-Eを観て、とても感激したのがもう1年近くも前になった（読み返してみましたが、なんだかずいぶんと稚拙な文章だなw）。<br />
				<a target="_blank" href="http://www.cocoalife.net/2008/12/post_771.html">cocoa*life &#8211; 「WALL-E」を観ました</a></p>
				<p>この映画はずっと以前からも生みたくてうずうずしていた。<br />
				はやる気持ちを抑え、初日の初回に観てきた。<br />
				WALL-Eを観たあのときも、とんでもない映画を観たなぁという思いがあったけれど、Pixarはそれを軽々と超えていったと思う。</p>
				<p>10月の終わりから11月の始めにかけて、これを書いているわずかひと月前、今まで生きてきた中で最低最悪で絶望的なことが起こり（それについては、来年のこの時期が来たら書くかもしれない）とても悲しみ、傷ついたから、余計映画の内容ともシンクロしてしまった。</p>
				<p>そのおかげか？途中で何度も何度も泣いた。<br />
				それでもこのことを差し引いても、とてもとてもすてきな映画だった。</p>
				<p>冒頭の愛妻との愛情溢れる倖せな生活、そして死。<br />
				言葉がないからなのか、心にすっとその倖せ、喜び、悲しみがしみいってくる。</p>
				<p>だからこそ、一見気むずかしそうに見えるカールじいさんが、どれだけの悲しみと後悔を携えて旅に出ようとしているのか観る人にはわかる。</p>
				<p>この映画の根底を流れる物語は「手放し」なのかもしれないと自分には映った。<br />
				愛する妻にしてあげられなかった二人の夢を叶え、後悔を手放すための物語。<br />
				これから大切にしてゆく周りの人たちを救うため、今まで頑なに拘っていたものを手放す物語。<br />
				執着しすぎた故、ついに望みを叶えられなかった人の物語。</p>
				<p>手放そうとするとき、人はいろいろな感情を感じ、今まで自分には何が大切だったのか、これからの自分には何が大切なのかということが見えてくる。</p>
				<p>人間の儚さ、悲しさ。<br />
				その一方で、愛そうとするときの強さ、優しさ、勇気。<br />
				いろいろな感情をたった一つの映画で見せてくれた。</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2009/12/post_848.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Snow Leopardでsyslogdが暴走したら。</title>
		<link>http://www.cocoalife.net/2009/12/post_847.html</link>
		<comments>http://www.cocoalife.net/2009/12/post_847.html#comments</comments>
		<pubDate>Thu, 03 Dec 2009 15:27:52 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Apple]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=847</guid>
		<description><![CDATA[				最近はファイルサーバをいろいろといじっています。
				FreeBSD 7.2 → FreeBSD 8のアップデートに失敗したため、もう一度サーバを再構築する必要が出てきてしまいました。
				このサーバはTimeMachineにも使用しているので、できるだけ早く直したいところです。
				あとから知ったことですが、FreeBSD 7.2でZFSを使っていた人はアップデート時に注意が必要とのことでした。
				詳細については以下のサイトに書いてあります。
				FreeBSD 7から8へ上げるZFS使いは気を付けろ &#8211; Cheerfull days
				[コンピュータ] FreeBSD-CURRENT をインストールしてみる &#8211; 2009-06-02 &#8211; くりてぃかるひっと！はてな分室
				その後、いろいろとiSCSIターゲットを構築したり、NFSサーバを構築したりしたものの、Mac OS X Snow Leopardから覗いてみたところ、設定の仕方が悪いのかちゃんと使用できない感じです。
				そのため強制的にアンマウント的なことをやったら、それ以降syslogdがCPU率100%で暴走してしまうようになりました。
				再起動してもダメ。
				さてどうしたものかなと思って、ぐぐってみるとLeopardへの対処法は書いてあるのですが、Snow Leopardに関してはありませんでした。
				具体的に書くと、/var/log/asl.dbというものを削除しろと書いてありますがそのファイルが見つからない。
				でも、/var/logを見てみると/var/log/aslというフォルダがある。
				どうもSnow Leopardからは単純なフォルダ構成になったようです。
				というわけで
				sudo launchctl unload /System/Library/LaunchDaemons/com.apple.syslogd.plist
sudo mv /var/log/asl ~/
sudo launchctl load /System/Library/LaunchDaemons/com.apple.syslogd.plist
				と/var/log/aslを移動してみると見事復活しました。
]]></description>
			<content:encoded><![CDATA[				<p>最近はファイルサーバをいろいろといじっています。<br />
				FreeBSD 7.2 → FreeBSD 8のアップデートに失敗したため、もう一度サーバを再構築する必要が出てきてしまいました。<br />
				このサーバはTimeMachineにも使用しているので、できるだけ早く直したいところです。</p>
				<p>あとから知ったことですが、FreeBSD 7.2でZFSを使っていた人はアップデート時に注意が必要とのことでした。<br />
				詳細については以下のサイトに書いてあります。</p>
				<p><a target="_blank" href="http://toga.vegalta.org/d/?0122">FreeBSD 7から8へ上げるZFS使いは気を付けろ &#8211; Cheerfull days</a><br />
				<a target="_blank" href="http://d.hatena.ne.jp/usaka/20090602#p1">[コンピュータ] FreeBSD-CURRENT をインストールしてみる &#8211; 2009-06-02 &#8211; くりてぃかるひっと！はてな分室</a></p>
				<p>その後、いろいろとiSCSIターゲットを構築したり、NFSサーバを構築したりしたものの、Mac OS X Snow Leopardから覗いてみたところ、設定の仕方が悪いのかちゃんと使用できない感じです。<br />
				そのため強制的にアンマウント的なことをやったら、それ以降syslogdがCPU率100%で暴走してしまうようになりました。<br />
				再起動してもダメ。</p>
				<p>さてどうしたものかなと思って、ぐぐってみるとLeopardへの対処法は書いてあるのですが、Snow Leopardに関してはありませんでした。<br />
				具体的に書くと、/var/log/asl.dbというものを削除しろと書いてありますがそのファイルが見つからない。</p>
				<p>でも、/var/logを見てみると/var/log/aslというフォルダがある。<br />
				どうもSnow Leopardからは単純なフォルダ構成になったようです。</p>
				<p>というわけで</p>
				<pre>sudo launchctl unload /System/Library/LaunchDaemons/com.apple.syslogd.plist
sudo mv /var/log/asl ~/
sudo launchctl load /System/Library/LaunchDaemons/com.apple.syslogd.plist</pre>
				<p>と/var/log/aslを移動してみると見事復活しました。</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2009/12/post_847.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grand Central Dispatchを試してみる。</title>
		<link>http://www.cocoalife.net/2009/09/post_845.html</link>
		<comments>http://www.cocoalife.net/2009/09/post_845.html#comments</comments>
		<pubDate>Wed, 02 Sep 2009 13:02:31 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=845</guid>
		<description><![CDATA[				]]></description>
			<content:encoded><![CDATA[				<p><a target="_blank href="http://www.apple.com/jp/macosx/technology/">Snow LeopardではOSの基礎部分にかなりの改良を加えた</a>と、Appleはいいます。<br />
				その基礎部分の改良の目玉機能の一つであるGrand Central Dispatchは、マルチコアでのプログラミングを簡単に行うためのフレームワークを提供してくれます。</p>
				<p>マルチコアでのプログラミングはいろいろと難しいことが多く自分は興味を持ったので、<a target="_blank" href="http://docs.komagata.org/4191">プログラムプレゼンテーションのネタ</a>に少し試してみることにしました。</p>
				<p>すでに最初の一歩を踏み出された方がいます。<br />
				<a target="_blank" href="http://blog.deadbeaf.org/2009/06/11/grand-central-dispatch/">Grand Central Dispatch at mootoh.log</a><br />
				<a target="_blank" href="http://blog.deadbeaf.org/2009/08/29/grand-central-dispatch-playground-1/">Grand Central Dispatch をためす at mootoh.log</a><br />
				<a target="_blank" href="http://d.hatena.ne.jp/pcmaster/20090830/p2">Grand Central Dispatchを試してみる &#8211; 理想未来はどうなった？</a></p>
				<p>dispatch_asyncというのは非同期に与えたブロックを実行するもので、<br />
				対してdispatch_syncというものは同期的にブロックを実行するものようです。</p>
				<p>この同期、非同期というものを自分はきちんと理解していないのですが、Concurrency Programming Guildeというドキュメントによると。。。</p>
				<dl class="quote">
				<dt>dispatch_async</dt>
				<dd>
				<blockquote>
				<p>Submits a block for asynchronous execution on a dispatch queue and returns immediately.</p>
				</blockquote>
				</dd>
				<dt>dispatch_sync</dt>
				<dd>
				<blockquote>
				<p>Submits a block object for execution on a dispatch queue and waits synchronously until that block completes.</p>
				</blockquote>
				</dd>
				<dt class="cite"> 引用元: <a href="http://developer.apple.com/mac/library/documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html">Grand Central Dispatch (GCD) Reference</a>
				</dt>
				</dl>
				<p>dispatch_syncはブロックが終了するまで待ってるよという風に見えます。</p>
				<p>上記のサンプルを参考にしつつ、ためしにこんなコードを書いてみました。</p>
				<pre class="brush: cpp;">
#include &lt;dispatch/dispatch.h&gt;
#include &lt;iostream&gt;
#include &lt;stdio.h&gt;
#include &lt;unistd.h&gt;

void c_hello(int count = 10)
{
	void (^hello)(int) = ^(int x)
	{
		printf(&quot;Hello, C World! %d\n&quot;, x);
	};

	for (int i = 0; i &lt; count; ++i)
	{
		dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
					   ^{
						   hello(i);
					   });
	}
}

void cpp_hello(int count = 10)
{
	void (^hello)(int) = ^(int x)
	{
		std::cout &lt;&lt; &quot;Hello, C++ World! &quot; &lt;&lt; x &lt;&lt; std::endl;
	};

	for (int i = 0; i &lt; count; ++i)
	{
		dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
					   ^{
						   hello(i);
					   });
	}
}

int main (int argc, char * const argv[])
{
	c_hello(1000);
	cpp_hello(1000);

	std::cout &lt;&lt; &quot;done!&quot; &lt;&lt; std::endl;

	// sleep がないと処理が終了する前に return してしまう。
	sleep(5);

    return 0;
}
</pre>
				<p>カリー化はブロックをブロックでくくればいいのでしょうか？</p>
				<p>わざとCのprintfとC++のstd::coutの両方を書いてみました。<br />
				面白かったのが1000回ループをさせたときでした。<br />
				10回では起こりませんでしたが、回数が増えるにつれ、C++の方はこんな風にごちゃ混ぜになりました。</p>
				<pre>Hello, C++ World! Hello, C++ World! Hello, C++ World! 974975976977978</pre>
<p>ちょっと考えてみると、<< 演算子で何個ものメソッドが入り組んでいる分、多数のスレッドが起動されるとこうなるのでしょう。</p>
<p>実際にプログラムプレゼンテーションで見せて、なにか簡単ないいサンプルがないと話してみたところ、<a target="_blank" href="http://cadr.g.hatena.ne.jp/g000001/">g000001さん</a>に<a target="_blank" href="http://ja.doukaku.org/215/nested/">疑似並行処理 どう書く？org</a>という課題をやってみてはどうか？というアドバイスをいただきました。</p>
<p>これがその解答になるかと思います。</p>
<pre class="brush: cpp;">
#include &lt;dispatch/dispatch.h&gt;
#include &lt;stdio.h&gt;
#include &lt;unistd.h&gt;

int main (int argc, char * const argv[])
{
    void (^alphabet)(int x) = ^(int x)
    {
        putchar('a' + x);
        putchar(' ');
    };

    void (^number)(int x) = ^(int x)
    {
        printf(&quot;%d &quot;, x);
    };

    for (int i = 0; i &lt; 26; ++i)
    {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{ alphabet(i); });
        dispatch_async(queue, ^{ number(i); });
    }

    printf(&quot;done!\n&quot;);
    sleep(5);

    return 0;
}
</pre>
				<p>結果は次のようになって、アルファベットと数字が無事混ざって表示されました。</p>
				<pre>done!
a 0 b 1 c 2 d 3 e 4 f 5 g 6 h 7 i 8 j 9 k 10 l 11 m 12 n 13 o 14 p 15 q 16 r 17 s 18 t 19 u 20 v 21 w 22 x 23 y 24 z 25
</pre>
				<p>これからは共有リソースをどうやって扱うことができるのか調べたいところです。</p>
				<p>P.S.<br />
				スレッド関連の用語を知らないので、適当に書いたところが多々あります。<br />
				うまく説明できないのが非常にもどかしいところです。</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2009/09/post_845.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
