2011-07-03 18 views
10

¿Cómo puedo encontrar una determinada cadena (valor) en un NSSet?
¿Se debe hacer esto usando predicados? ¿Si es así, cómo?Búsqueda NSString en NSSet

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]]; 

Ahora quiero comprobar si existe 'String 2' en el conjunto.

Respuesta

6

De Apple's Developer Site:

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 contiene algo más de información sobre el uso de predicados. Finalmente, Apple's BNF guide for predicates contiene información sobre todas las operaciones que uno podría necesitar.

+0

la respuesta a continuación es más de lo que yo esperaba, pero gracias por presentarme a NSPredicar! –

2

might member: work here?

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

Las cadenas son iguales si sus contenidos son iguales, por lo que sólo pueden hacer:

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

usando un NSPredicate aquí es una exageración, porque NSSet ya tiene un método y un método -member:-containsObject:.

+11

Estrictamente hablando, no es verdad que las cadenas sean iguales (en el sentido de ANSI C) si sus contenidos son iguales. Las cadenas son iguales si sus valores de puntero son iguales. Sin embargo, es cierto que no necesita un Predicado, porque los métodos '-member:' y '- containsObject:' no comparan los objetos, pero llama al método -isEqual: que en el caso de NSStrings realmente comparar los contenidos de los objetos, no los objetos mismos. – KPM

+10

@ KPM, excepto que este no es ANSI C, este es Objective-C, donde la clase 'NSString' ha anulado el método' -isEqual: 'para hacer una comparación' strcmp' -like entre las dos cadenas. Tan estrictamente hablando, dos cadenas son iguales si sus contenidos son iguales. (No estoy hablando de identidad, que es lo que obtienes de dos punteros son los mismos) –

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

Puede o no funcionar. El compilador puede o no puede crear diferentes objetos de la misma @ "" cadena, así que preferiría hacerlo con mathces predicado:

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