NSArrayで特定の文字列を検索したいと思います。
例:
NSArrayには、「dog」、「cat」、「fat dog」、「thing」、「anotherthing」、「heckhere'sanotherthing」というオブジェクトがあります。
「another」という単語を検索して結果を1つの配列に入れ、もう1つの非結果を、さらにフィルタリングできる別の配列に入れたいと思います。
配列内の文字列が異なることがわかっている場合は、セットを使用できます。NSSetは、大きな入力ではNSArrayよりも高速です。
NSArray * inputArray = [NSMutableArray arrayWithObjects:@"one", @"two", @"one again", nil];
NSMutableSet * matches = [NSMutableSet setWithArray:inputArray];
[matches filterUsingPredicate:[NSPredicate predicateWithFormat:@"SELF contains[c] 'one'"]];
NSMutableSet * notmatches = [NSMutableSet setWithArray:inputArray];
[notmatches minusSet:matches];
テストされていないため、構文エラーが発生する可能性がありますが、アイデアは得られます。
NSArray* inputArray = [NSArray arrayWithObjects:@"dog", @"cat", @"fat dog", @"thing", @"another thing", @"heck here's another thing", nil];
NSMutableArray* containsAnother = [NSMutableArray array];
NSMutableArray* doesntContainAnother = [NSMutableArray array];
for (NSString* item in inputArray)
{
if ([item rangeOfString:@"another"].location != NSNotFound)
[containsAnother addObject:item];
else
[doesntContainAnother addObject:item];
}
ドキュメントごとに「indexOfObjectIdenticalTo:」は、渡したオブジェクトと同じメモリアドレスを持つ最初のオブジェクトのインデックスを返すため、機能しません。
配列をトラバースして比較する必要があります。