Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
)
like image 407
John Erck Avatar asked Jul 11 '12 18:07

John Erck


People also ask

How do you remove an empty string from an array?

To remove the empty strings from an array, we can use the filter() method in JavaScript. In the above code, we have passed the callback function e => e to the filter method, so that it only keeps the elements which return true . empty "" string is falsy value, so it removes from the array.

How do you delete an object in NSArray?

NSArray is not editable, so that you cannot modify it. You can copy that array to NSMutableArray and remove objects from it. And finally reassign the values of the NSMutableArray to your NSArray.

What is NSArray in Swift?

In Swift, the NSArray class conforms to the ArrayLiteralConvertible protocol, which allows it to be initialized with array literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).


1 Answers

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:.

like image 136
Nikolai Ruhe Avatar answered Nov 15 '22 18:11

Nikolai Ruhe