LoginSignup
1
1

More than 5 years have passed since last update.

キーに予約語があるときのNSPredicateの作り方

Posted at

外部から取得したなどのデータのなかに
NSDictionary *dict = @{ @"no" : @(0) };
のようにNumberをnoと省略して登録されていたため、NSPredicateの作成が出来ないと言うことがあります。

上の場合、たとえば

NSArray *array = @[
    @{ @"no" : @(0) },
    @{ @"no" : @(9) },
    @{ @"no" : @(32) }
    ];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"no = %@", @(9)];

NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
NSLog(@"%@", filteredArray);

としても、予想に反しfilteredArrayは空になります。
これは no が Boolean の NO として処理され、すべてのデータが偽となるからです。

処々の事情でキーnoの変更が出来ない場合、大変困ります。
しかし、NSPredicateの書式に含まれる %K を利用することでキーがnoのままでも正しいNSPredicateの作成が可能です。
%Kは「ここに入るものはkeyです」という書式です。

上の場合は、こうすれば作成可能です。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K = %@", @"no", @(9)];

%Kを使用すれば ANDやORなどの予約語もキーとして使用可能です。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1