Dan*_*elR 2 objective-c nsarray nspredicate ios
我有一个包含字符串的数组.其中一些字符串可能为空(@"").谓词必须如何看起来过滤数组并返回一个只包含非空字符串的新数组:
数组A:{"A","B","","D"} - >过滤器 - >数组B:{"A","B","D"}
它也应该返回:
数组A:{"","","",""} - >过滤器 - >数组B:{}
Luk*_*cka 10
SELF != ''如果您只过滤NSStrings 数组,请使用谓词.这匹配每个NSString不完全等于空字符串.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF != ''"];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
Run Code Online (Sandbox Code Playgroud)
示例代码:
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:@","]);
Run Code Online (Sandbox Code Playgroud)
给出这个输出
Input array: A,B,,C,,D
Filtered array: A,B,C,D
Run Code Online (Sandbox Code Playgroud)
编辑:Joris Kluivers发布了谓词格式的解决方案length > 0.这可能是更好的解决方案,只是为了删除空字符串,因为它可能会更快.
检查字符串的长度:
NSArray *values = @[@"A", @"B", @"", @"D"];
NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"length > 0"];
NSArray *filteredValues = [values filteredArrayUsingPredicate:filterPredicate];
Run Code Online (Sandbox Code Playgroud)
结果在所需的数组中 ("A", "B", "C")
| 归档时间: |
|
| 查看次数: |
8231 次 |
| 最近记录: |