Cerca tramite nsarray per la stringa
Domanda
Vorrei cercare attraverso il mio nsarray per una certa stringa.
Esempio:
Nsarray ha gli oggetti: "cane", "gatto", "fat cane", "cosa", "un'altra cosa", "diamine ecco un'altra cosa"
Voglio cercare la parola "un altro" e mettere i risultati in un array e avere l'altro, non risultati, in un altro array che può essere filtrato ulteriormente.
Soluzione
Non testato, quindi potrebbe avere un errore di sintassi, ma avrai l'idea.
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];
}
Altri suggerimenti
Se le stringhe all'interno dell'array sono note per essere distinte, è possibile utilizzare i set. NSSET è più veloce di NSARRAY su ingressi di grandi dimensioni:
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];
Non funzionerebbe perché, secondo il documento "INDICEFObjectidicalto:" Restituisce l'indice del primo oggetto che ha lo stesso indirizzo di memoria dell'oggetto in cui stai trasmettendo.
Devi attraversare il tuo array e confrontare.