2016-10-11 5 views
0

私は辞書のNSMutableArrayを持っています。私は特定のキーを持つ辞書が存在するかどうかを見つけるために配列をフィルタリングするためにNSPredicateを使用しています。NSPredicateを使用してNSDictionaryのNSMutableArrayをフィルタリングし、 "key"が存在するかどうかを確認します。

私はいろいろな例を紹介しましたが、最も近いものはUsing NSPredicate to filter an NSArray based on NSDictionary keysです。しかし、私はキーに価値を持たせたくありません。私の問題は、私が最初に鍵を探したいということです。私は異なる構文を試しましたが、それは助けにはなりませんでした。私がこれまで行ってきた何

NSString *key = @"open_house_updated_endhour"; 
    NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K", key]; 
    //NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K contains [cd]", key]; Doesn't work. 
    //NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K == %@", key]; Won't work because it expects a value here. 
    NSLog(@"predicate %@",predicateString); 
    NSArray *filtered = [updatedDateAndTime filteredArrayUsingPredicate:predicate]; // updatedDateAndTime is the NSMutableArray 
+0

だから、「特定のキー」が配列に含まれている辞書に存在するかどうかを知りたいのですか? – Adeel

+0

@AdeelMirajはい、まさに!それが私が望むものです。 – Ron

+0

私の意見では、配列を列挙することは、これを行う比較的簡単で簡単な方法です。述語を使ってこれを行う特別な理由はありますか? – Adeel

答えて

3

辞書は存在しないキーの値としてnil提供します。キーをnilと比較するだけです。

NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K==NULL", key]; // Dictionaries not having the key 
NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K!=NULL", key]; // Dictionaries having the key 
+0

すみません、ありがとうございました。それは助けになった。必要な辞書オブジェクトがある場合は、配列を取得します。 @ "%K == NULL"を使用する場合はどうすればよいですか? @ "%K!= NULL"?私がこれを行うと、私はエラーが発生します。基本的に、キーが見つかると辞書を更新したいと思います。それが空であるかどうかは関係ありません。間違いなく、私はこの単純な解決が好きです。 – Ron

+0

私はなぜあなたが '@"%K == NULL "||を使用したいのか分かりません。 @ "%K!= NULL"です。まず、最初の '' NULL'の後に余分な '' 'があります。エラーとは何ですか?あなたはエラーを教えてくれますか?しかし、表現は常に真実です。 –

0

はそれを試してみてください。

NSArray *Myarray = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"my hello string" forKey:@"name"]]; 
NSArray *filteredarray = [Myarray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(name == %@)", @"my hello string"]]; 
NSLog("%@",filteredarray); 

別の例は:

NSString *mycategory = @"iamsomeone"; 
NSArray *myitems = @[@{ @"types" : @[@"novel", @"iamsomeone", @"dog"] }, 
        @{ @"types" : @[@"cow", @"iamsomeone-iam", @"dog"] }, 
        @{ @"types" : @[@"cow", @"bow", @"cat"] }]; 
NSPredicate *mypredicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) { 
    NSArray *categories = [evaluatedObject objectForKey:@"types"]; 
    return [categories containsObject:mycategory]; 
}]; 

NSArray *outpuArray = [myitems filteredArrayUsingPredicate:mypredicate]; 
NSLog(@"hello output:%@",outpuArray); 
+0

迅速な対応をありがとう。ただし、最初の例では、キーの値が必要です。私の場合、それはそこにあってもなくてもよい。したがって、まずキーを確認したいと思います。 – Ron

関連する問題