macOS/iOS API解説

iOS , Mac アプリケーション開発のために使われる主要フレームワークの日本語情報です。2010年代に書かれた内容です。今後更新はありません。

目次

NSPredicateクラス

INDEX>Foundation>

apple(OS X)
apple(iOS)

解説

継承 NSObject
準拠 NSObject (NSObject)
フレームワーク /System/Library/Frameworks/Foundation.framework
使用可能 OS X 10.4以降
iOS 3.0以降
定義 NSPredicate.h

概要

検索などに使う条件式のクラスです。
SQLのような条件式や正規表現式、ブロックオブジェクトを使ってObjective-Cで独自の条件を書くことができます。

詳細はSQL正規表現の解説書を見ていただいた方が詳しいですが式の一例を下記に挙げておきます。

aが入った要素だけを抽出
SELF LIKE '*a*'

値が6または9のものを抽出
SELF == 6 OR SELF == 9

ageという名前のついたプロパティ(または辞書のキー)の値が0から19までの間にあるか。
age BETWEEN {0, 19}

正規表現式を使った抽出
SELF matches [aaa|bbb]+

作成

フォーマット文字列からNSPredicateオブジェクトを作成するには(+ predicateWithFormat)メソッドを使用します。複数の引数を用いてフォーマット文字列からNSPredicateオブジェクトを作成するには(+ predicateWithFormat:argumentArray)メソッドを使用します。va_listとフォーマット文字列からNSPredicateオブジェクトを作成するには(+ predicateWithFormat:arguments)メソッドを使用します。

変数を含むNSPredicateオブジェクトを作成するには(– predicateWithSubstitutionVariables:)を使用します。

変数を含むテンプレートからNSPredicateオブジェクトを作成

#pragma mark NSPredicate predicateWithSubstitutionVariables
-(void)method007
{
    //ダミーの人データを作成、苗字・名前・年齢
    NSDictionary *tanaka = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:30],@"age" ,
                            @"Tanaka",@"lastName",@"Taro",@"firstName",nil];
    NSDictionary *sato = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:43],@"age" ,
                          @"Sato",@"lastName",@"Satoko",@"firstName",nil];
    NSDictionary *suzuki = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:39],@"age" ,
                            @"Suzuki",@"lastName",@"Ichiro",@"firstName",nil];
    NSDictionary *yamada = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:12],@"age" ,
                            @"Yamada",@"lastName",@"Jiro",@"firstName",nil];
    NSArray *anArray =
    [[NSArray alloc] initWithObjects:tanaka,sato,suzuki,yamada,nil];
    
    
    //テンプレート作成
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"$minAge <= age AND age < $maxAge"];

    //年齢条件作成
    NSNumber *min = [NSNumber numberWithInteger:10];
    NSNumber *max = [NSNumber numberWithInteger:35];
    NSDictionary *variables = [NSDictionary dictionaryWithObjectsAndKeys:min, @"minAge", max, @"maxAge", nil];
    //テンプレートを利用して条件式を作成
    NSPredicate *bPredicate = [predicate predicateWithSubstitutionVariables:variables];
    //検索
    NSArray *bResult = [anArray filteredArrayUsingPredicate:bPredicate];
    NSLog(@"%s %@",__FUNCTION__,[bResult description]);
}

ブール値でYESかNOかのNSPredicateオブジェクトを作成するには(+ predicateWithValue)メソッドを使用します。デフォルトではすべて選択、場合によって条件を設定するときなどに使用します。

条件式ではなく比較条件をブロックオブジェクトとして記述してNSPredicateオブジェクトとして使うことができます。(+ predicateWithBlock)メソッドで作成します。

ブロックを使ったNSPredicateオブジェクトの作成

#pragma mark NSPredicate  predicateWithBlock:
-(void)method009
{
    NSArray *anArray =
    [[NSArray alloc] initWithObjects:   @"abc",@"def",@"ghi",
     @"ihg",@"fed",@"cba",
     @"aaa",@"bbb",@"ccc",nil];

     NSPredicate* aPredicate = [NSPredicate predicateWithBlock:
                      ^BOOL(id obj, NSDictionary *d) {
                          NSString* s = obj;
                          //NSLog(@"%s %@",__FUNCTION__,[d description]);
                          return ([s rangeOfString:@"a"
                                           options:NSCaseInsensitiveSearch].location != NSNotFound);
                      }];
    
    
    NSArray *aResult = [anArray filteredArrayUsingPredicate:aPredicate];
    NSLog(@"%s %@",__FUNCTION__,[aResult description]);
    
}

表現式の評価

正規表現式を使って与えたオブジェクトが条件にマッチするかを調べるには(– evaluateWithObject)メソッドを使用します。変数を使うことができるメソッド(– evaluateWithObject:substitutionVariables:)もあります。

変数を使った正規表現式の作成

#pragma mark NSPredicate evaluateWithObject
-(void)method011
{
    NSString *string1 = @"bbb";
    
    //テンプレート作成
    NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"SELF matches  $string1"];
    
    //変数辞書作成
    NSDictionary *variables1 = [NSDictionary dictionaryWithObjectsAndKeys:@"bbb", @"minAge", @"aaa", @"string1", nil];
    NSDictionary *variables2 = [NSDictionary dictionaryWithObjectsAndKeys:@"bbb", @"minAge", @"bbb", @"string1", nil];
    
    //テンプレートを利用して条件式を作成
    NSPredicate *bPredicate = [aPredicate predicateWithSubstitutionVariables:variables1];
    NSPredicate *cPredicate = [aPredicate predicateWithSubstitutionVariables:variables2];
    
    //チェック用
    NSLog(@" %s %@", __FUNCTION__,([aPredicate evaluateWithObject:string1 substitutionVariables:variables1])?@"YES":@"NO");
    NSLog(@" %s %@", __FUNCTION__,([aPredicate evaluateWithObject:string1 substitutionVariables:variables2])?@"YES":@"NO");
    //デバッグ用
    NSLog(@" %s %@", __FUNCTION__,[bPredicate predicateFormat]);
    NSLog(@" %s %@", __FUNCTION__,[cPredicate predicateFormat]);
}

条件式の表示

レシーバが持っている条件式を文字列にして返すには(– predicateFormat)メソッドを使用します。

適合するプロトコル