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: {}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With