如何在两个不同的密钥的NSDictionary NSArray之间找到数字

时间:2017-09-28 05:41:45

标签: ios objective-c nspredicate

这是我的代码段:

NSMutableArray *arrTableData = [NSMutableArray new];

[arrTableData addObject:@{@"from":[NSNumber numberWithDouble:700], @"to":[NSNumber numberWithDouble:760]}];

[arrTableData addObject:@{@"from":[NSNumber numberWithDouble:760], @"to":[NSNumber numberWithDouble:820]}];

[arrTableData addObject:@{@"from":[NSNumber numberWithDouble:820], @"to":[NSNumber numberWithDouble:940]}];

[arrTableData addObject:@{@"from":[NSNumber numberWithDouble:940], @"to":[NSNumber numberWithDouble:990]}];

我希望仅使用number == 800查找NSPredicate

案例:1

NSNumber *number = [NSNumber numberWithDouble:940];

NSPredicate *subQuery1 = [NSPredicate predicateWithFormat:@"from >= %@ OR to < %@",number,number];

NSArray *filteredArray = [arrTableData filteredArrayUsingPredicate:subQuery1];
  • 我不喜欢使用循环 enumerateObjectsUsingBlock

4 个答案:

答案 0 :(得分:0)

反过来说。

谓词必须大于或等于from且小于to

NSNumber *number = @800.0;
NSPredicate *subQuery1 = [NSPredicate predicateWithFormat:@"from <= %@ AND to > %@", number, number];

[NSPredicate predicateWithFormat:@"%@ >= from AND %@ < to", number, number];

答案 1 :(得分:0)

试试这个,

NSMutableArray *arrTableData = [NSMutableArray new];

[arrTableData addObject:@{@"from":[NSNumber numberWithDouble:700], @"to":[NSNumber numberWithDouble:760]}];

[arrTableData addObject:@{@"from":[NSNumber numberWithDouble:760], @"to":[NSNumber numberWithDouble:820]}];

[arrTableData addObject:@{@"from":[NSNumber numberWithDouble:820], @"to":[NSNumber numberWithDouble:940]}];

[arrTableData addObject:@{@"from":[NSNumber numberWithDouble:940], @"to":[NSNumber numberWithDouble:990]}];

NSLog(@"%@",arrTableData);

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"from >= 800"];

NSArray  *filterdArray = [[arrTableData filteredArrayUsingPredicate:predicate] mutableCopy];

NSLog(@"filter arr : %@",filterdArray);

它会给出大于或等于800的字典数组!

答案 2 :(得分:0)

试试这个:

NSArray *resultArray = [arrTableData filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(from >= %@) OR (to < %@)", @800,@800]];

过滤to < 800

NSArray *resultArray2 = [arrTableData filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(from < %@)", @800]];

答案 3 :(得分:0)

这并没有为之前的答案添加任何内容,但您真的应该考虑对Objective-C代码进行现代化。您问题中的代码可以简化为......

NSMutableArray *arrTableData = [NSMutableArray new];
[arrTableData addObjectsFromArray: @[@{@"from":@700.0, @"to":@760.0},
                                     @{@"from":@760.0, @"to":@820.0},
                                     @{@"from":@820.0, @"to":@940.0},
                                     @{@"from":@940.0, @"to":@990.0}]];

您可以通过选择编辑 - &gt;轻松完成此操作。转换 - &gt;到现代Objective-C语法......

enter image description here