[objective-c]ios NSPredicate 来查找最近的 NSDictionary 中的值

发布时间: 2016/10/2 10:48:52
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有字典数组如下所示︰

(
{ key = 1, value = 40},
{ key = 4, value = 50},
{ key = 8, value = 60}
}

这些都是这样, for >=1 项目成本是 40for >=4 项目成本是 50和像智慧人。

要获取的值 5,而在这种情况下是 50 !

我用过段是代码的︰

NSMutableArray *wallpaperPriceArray = [[NSMutableArray alloc]init]; // Assuming this has all the dictionary values 

float wallpaperPriceValue = 0;

int itemNumber = 0;

for (int i = 0; i<wallpaperPriceArray.count; i++) {

int check = 0;

if(itemNumber >= [[wallpaperPriceArray objectAtIndex:i] intValue])
{
    wallpaperPriceValue = [[[wallpaperPriceArray objectAtIndex:i] objectForKey:@"value"] floatValue];
    check++;
}

if(i + 1 <= wallpaperPriceArray.count)
{
    if(itemNumber >= [[wallpaperPriceArray objectAtIndex:i+1] intValue] && itemNumber < [[wallpaperPriceArray objectAtIndex:i+1] intValue])
    {
        wallpaperPriceValue = [[[wallpaperPriceArray objectAtIndex:i+1] objectForKey:@"value"] floatValue];
        check++;

        if(check == 2)
        {
            break ;
        }
    }
}

if(i + 2 <= wallpaperPriceArray.count)
{
    if(itemNumber >= [[wallpaperPriceArray objectAtIndex:i+2] intValue] && itemNumber < [[wallpaperPriceArray objectAtIndex:i+2] intValue])
    {
        wallpaperPriceValue = [[[wallpaperPriceArray objectAtIndex:i+2] objectForKey:@"value"] floatValue];
        check++;

        if(check == 2)
        {
            break ;
        }
    }
}

解决方法 1:

我不认为该谓词是正确的事,更好地将枚举对象在这里是一些示例代码︰

NSArray *array = @[
                   @{ @"key" : @(1), @"value" : @(40)},
                   @{ @"key" : @(4), @"value" : @(50)},
                   @{ @"key" : @(8), @"value" : @(60)}
];

NSInteger searchedValue = 5; // <---

__block NSDictionary *closestDict = nil;
__block NSInteger closestValue = 0;


[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSDictionary *dict = obj;
    NSInteger key = [dict[@"key"] integerValue];

    // Check if we got better result
    if(closestDict == nil || (key > closestValue && key <= searchedValue)){
        closestDict = dict;
        closestValue = key;

        if(key == searchedValue) { *stop = YES; }
    }
}];

NSLog(@"value %@", closestDict);
官方微信
官方QQ群
31647020