2011-07-03 20 views
10

NSSetで特定の文字列(値)を見つける方法はありますか?
これは述語を使用して行う必要がありますか?もしそうなら、どうですか?NSSetのNSStringルックアップ

NSMutableSet *set = [[NSMutableSet alloc] init]; 
[set addObject:[[[NSString alloc] initWithFormat:@"String %d", 1] autorelease]]; 
[set addObject:[[[NSString alloc] initWithFormat:@"String %d", 2] autorelease]]; 
[set addObject:[[[NSString alloc] initWithFormat:@"String %d", 3] autorelease]]; 

「文字列2」がセットに存在するかどうかを確認したいと思います。 Apple's Developer Siteから

答えて

6

NSSet *sourceSet = [NSSet setWithObjects:@"One", @"Two", @"Three", @"Four", nil]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith 'T'"]; 
NSSet *filteredSet = [sourceSet filteredSetUsingPredicate:predicate]; 
// filteredSet contains (Two, Three) 

This article from Ars Technicaは、述語を使用してのいくつかのより多くの情報が含まれています。最後にApple's BNF guide for predicatesには、必要なすべての操作に関する情報が含まれています。

+0

以下の答えは私が望んで、それに私を導入するためのありがとう何よりですNSPredicate! –

2

メンバー:ここで働く?その内容が等しい場合

member: 
Determines whether the set contains an object equal to a given object, and returns that object if it is present. 

- (id)member:(id)object 
Parameters 
object 
The object for which to test for membership of the set. 
Return Value 
If the set contains an object equal to object (as determined by isEqual:) then that object (typically this will be object), otherwise nil. 

Discussion 
If you override isEqual:, you must also override the hash method for the member: method to work on a set of objects of your class. 

Availability 
Available in iOS 2.0 and later. 
Declared In 
NSSet.h 
43

文字列は同じなので、あなただけ行うことができます。

NSSet *set = [NSSet setWithObjects:@"String 1", @"String 2", @"String 3", nil]; 
BOOL containsString2 = [set containsObject:@"String 2"]; 

ここNSPredicateを使用してNSSetはすでに-member:方法と-containsObject:方法を持っているので、やり過ぎです。

+11

厳密には、内容が等しい場合、文字列が(ANSI Cの意味で)等しいことは真実ではありません。ポインタ値が等しい場合、文字列は等しいです。しかし、 '-member:'と ' - containsObject:'メソッドはオブジェクトを比較せず、-isEqual:メソッドを呼び出すため、Predicateは必要ありません。これはNSStringsの場合には実際にはオブジェクト自体の内容ではなく、オブジェクトの内容を比較します。 – KPM

+10

@KPMこれはANSI C以外のObjective-Cですが、 'NSString'クラスは' -isEqual: 'メソッドをオーバーライドして2つの文字列間の' strcmp'のような比較を行います。厳密に言えば、内容が等しい場合、2つの文字列は等しいです。 (私は同一性について話しているわけではありません。これは、2つのポインタが同じものです) –

1
NSSet *set = [NSSet setWithObjects:@"String 1", @"String 2", @"String 3", nil]; 
BOOL containsString2 = [set containsObject:@"String 2"];

5月または動かないことがあります。コンパイラは、または「」@同じのための文字列を別のオブジェクトを作成しない場合がありますので、私はむしろ、MATHCES述語でそれを行うだろう:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"String 2"];