2014/04/05

[iOS]カメラ勉強備忘録 - その2(CIDetector のメモリリーク)

こんばんわ!
あまりブログを書けてませんが、粛々と勉強中です。

CIDetector を使用して顔認識までは無事出来ました。
が、CIDetector のメモリリークにはまったのでメモ。
( iOS7.1 SDK を使用 )

captureOutput:didOutputSampleBuffer:fromConnection: メソッドで
取得したすべてのカメラ画像に対して顔認識しています。
その際、CIDetector は生成する際のコストが高いため使い回わしていましたが、
これがまずかった。

static CIDetector *detector = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    detector = [CIDetector detectorOfType:CIDetectorTypeFace
                                  context:nil
                                  options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
});
    
NSDictionary *options = @{
                          CIDetectorSmile: @(YES),
                          CIDetectorEyeBlink: @(YES),
                          };
    
NSArray *features = [detector featuresInImage:ciImage options:options];


同一の CIDetector インスタンスに対して featuresInImage: メソッドの実行を
繰り返すと、毎回メモリリーク( CIDetector のバグ?)していき、
最終的にはアプリが強制終了した。

回避方法としては、CIDetector インスタンスを毎回生成するように修正する。

 CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeFace
                                           context:nil
                                           options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
        
 NSDictionary *options = @{
                           CIDetectorSmile: @(YES),
                           CIDetectorEyeBlink: @(YES),
                           };
        
 NSArray *features = [detector featuresInImage:ciImage options:options];

これで、OK!
性能は悪くなるが、仕方なしとしよう。