John Erck John Erck - 5 months ago 14
Objective-C Question

What's the easiest way to remove empty NSStrings from an NSArray?

In PHP it's one line of code:

$array_without_empty_strs = array_filter($array_with_empty_strs);


What's the objective C equivalent?

UPDATE - Added the following test code to illustrate the use of Nikolai Ruhe's solution:

// SOLUTION Test Code
NSMutableArray *myArray = [[NSMutableArray alloc] init ];
[myArray addObject:[NSNumber numberWithInt:5]];
[myArray addObject:@""];
[myArray addObject:@"test"];
NSLog(@"%@", myArray);
[myArray removeObject:@""];
NSLog(@"%@", myArray);

// SOLUTION Test Code Output
2012-07-12 08:18:16.271 Calculator[1527:f803] (
5,
"",
test
)
2012-07-12 08:18:16.273 Calculator[1527:f803] (
5,
test
)

Answer

It's even more simple:

[mutableArrayOfStrings removeObject:@""];

If your array is not mutable you have to create a mutableCopy before.

removeObject: removes all objects from an array that return YES from isEqual:.

Comments