4

タイトルがややこしいです…説明します

私はオブジェクトを取り込んNSMutableArrayでいNSMutableDictionaryます。私がやろうとしているのは、辞書オブジェクトが配列に追加される前に、既に設定されている id と等しい値が辞書に含まれているかどうかを確認する必要があることです。

例:

ステップ 1: ボタンをクリックして、ビューの確立に使用するオブジェクトの ID を設定します。

ステップ 2: 上記のビュー内で別のボタンを押して、そのコンテンツの一部を辞書に保存し、その辞書を配列に追加します。ただし、確立された ID が辞書キーの値として既に存在する場合は、この辞書を挿入しないでください。

現在動作していないコードを次に示します。

-(IBAction)addToFavorites:(id)sender{
    NSMutableDictionary *fav = [[NSMutableDictionary alloc] init];
    [fav setObject:[NSNumber numberWithInt:anObject.anId] forKey:@"id"];
    [fav setObject:@"w" forKey:@"cat"];

    if ([dataManager.anArray count]==0) {     //Nothing exists, so just add it
        [dataManager.anArray addObject:fav];
    }else {
        for (int i=0; i<[dataManager.anArray count]; i++) {
            if (![[[dataManager.anArray objectAtIndex:i] objectForKey:@"id"] isEqualToNumber:[NSNumber numberWithInt:anObject.anId]]) {
                [dataManager.anArray addObject:fav];
            }       
        }
    }
    [fav release];
}
4

1 に答える 1

7

この種のチェックを行うかなり簡単な方法の 1 つは、NSPredicate を使用して配列をフィルタリングすることです。一致するものがない場合、フィルタリングの結果は空の配列になります。たとえば、次のようになります。

NSArray *objs = [dataManager anArray];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id == %@", [NSNumber numberWithInt:i]];
NSArray *matchingObjs = [objs filteredArrayUsingPredicate:predicate];

if ([matchingObjs count] == 0)
{
    NSLog(@"No match");
}
于 2010-09-14T15:45:50.520 に答える