10

NSDictionary を含む次の NSArray があります。

NSArray *data = [[NSArray alloc] initWithObjects:
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1], @"bill", [NSNumber numberWithInt:2], @"joe", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:3], @"bill", [NSNumber numberWithInt:4], @"joe", [NSNumber numberWithInt:5], @"jenny", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:6], @"joe", [NSNumber numberWithInt:1], @"jenny", nil],
                 nil];

NSPredicate を使用して、NSDictionary が複数の「キー」と一致するオブジェクトのみを含む、フィルター処理された NSArray を作成したいと考えています。

例えば:

  • キー「bill」と「joe」を持つ NSDictionary オブジェクトのみが含まれるように配列をフィルタリングします [望ましい結果: 新しい NSArray には最初の2 つの NSDictionary オブジェクトが含まれます]
  • キー「joe」と「jenny」を持つ NSDictionary オブジェクトのみが含まれるように配列をフィルター処理します [望ましい結果: 新しい NSArray には最後の2 つの NSDictionary オブジェクトが含まれます]

これを達成するための NSPredicate の形式を誰か説明してもらえますか?

編集:次を使用して、目的の NSPredicate と同様の結果を達成できます。

NSMutableArray *filteredSet = [[NSMutableArray alloc] initWithCapacity:[data count]];
NSString *keySearch1 = [NSString stringWithString:@"bill"];
NSString *keySearch2 = [NSString stringWithString:@"joe"];

for (NSDictionary *currentDict in data){
    // objectForKey will return nil if a key doesn't exists.
    if ([currentDict objectForKey:keySearch1] && [currentDict objectForKey:keySearch2]){
        [filteredSet addObject:currentDict];
    }
}

NSLog(@"filteredSet: %@", filteredSet);

NSPredicate が存在する場合、よりエレガントになると想像していますか?

4

2 に答える 2