HurkNburkS
HurkNburkS

Reputation: 5510

How to remove item from NSArray depending on the items contents

I am creating an NSArray of NSStrings, however one of the arrays that is entered is a set of quotation marks:

""

I would like to know hot to exclude these from my array, I have tried using a predicate but it's not working.

This is what my code looks like:

NSString *tempSymbolsString = [tempAxesDictionary objectForKey:@"Symbols"];
        NSArray *tempSymbolsArray = [tempSymbolsString componentsSeparatedByString:@";"];
        tempSymbolsArray = [symbolsArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != """""]];
        NSLog(@"%@", tempSymbolsArray);

Upvotes: 0

Views: 226

Answers (2)

Alladinian
Alladinian

Reputation: 35636

Actually is even simpler than this. Since you only got strings in your array, create a mutable copy and remove all occurrences of "". Something like this perhaps:

NSMutableArray *temp = [tempSymbolsArray mutableCopy];
[temp removeObject:@"\"\""];

This works since removeObject: will compare objects via isEqual: and remove any matches.

Upvotes: 2

rmaddy
rmaddy

Reputation: 318824

Do it yourself:

NSString *tempSymbolsString = tempAxesDictionary[@"Symbols"];
NSMutableArray *symbolsArray = [[tempSymbolsString componentsSeparatedByString:@";"] mutableCopy];
for (NSUInteger i = symbolsArray.count; i > 0; i--) {
    if ([symbolsArray[i - 1] isEqualToString:@"\"\""]) {
        [symbolsArray removeObjectAtIndex:i - 1];
    }
}

At the end the symbolsArray will have all values except those matching "".

BTW - your original predicate probably needs a bunch of escaping:

[NSPredicate predicateWithFormat:@"SELF != \"\\\"\\\"\""]

Upvotes: 0

Related Questions