Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter NSArray using NSPredicate [closed]

I have an array which contains strings. Some of these string might be empty (@""). How does the predicate have to look like so that it filters the array and returns a new one containing only non empty strings:

Array A: {"A","B","","D"} -> FILTER -> Array B: {"A","B","D"}

and it should also return this:

Array A: {"","","",""} -> FILTER -> Array B: {}

like image 933
DanielR Avatar asked Feb 24 '26 12:02

DanielR


1 Answers

Use predicate SELF != '' if you are filtering just array of NSStrings. This matches every NSString which is not exactly equal to empty string.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF != ''"];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];

Example code:

NSArray *array = @[@"A", @"B", @"", @"C", @"", @"D"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF != ''"];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
NSLog(@"Input array: %@\nFiltered array: %@", [array componentsJoinedByString:@","], [filteredArray componentsJoinedByString:@","]);

Gives this output

Input array: A,B,,C,,D
Filtered array: A,B,C,D

Edit: Joris Kluivers posted solution with predicate format length > 0. This is probably better solution just for removing empty string as it will probably be much faster.

like image 123
Lukas Kukacka Avatar answered Feb 26 '26 09:02

Lukas Kukacka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!