ios NSPredicate 在 NSDictionary 中查找最接近的值
<p><p>我有一个 <strong>字典数组</strong>,如下所示:</p>
<pre><code>(
{ key = 1, value = 40},
{ key = 4, value = 50},
{ key = 8, value = 60}
}
</code></pre>
<p>这些是这样的,
<code>for >=1</code> <em>项目成本是 40</em>,
<code>for >=4</code> <em>项目成本是 50</em> 和类似的。</p>
<p>我想获得 5 的值,在本例中为 50。</p>
<p>我试过的一段代码是:</p>
<pre><code>NSMutableArray *wallpaperPriceArray = [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 >= [ intValue])
{
wallpaperPriceValue = [[ objectForKey:@"value"] floatValue];
check++;
}
if(i + 1 <= wallpaperPriceArray.count)
{
if(itemNumber >= [ intValue] && itemNumber < [ intValue])
{
wallpaperPriceValue = [[ objectForKey:@"value"] floatValue];
check++;
if(check == 2)
{
break ;
}
}
}
if(i + 2 <= wallpaperPriceArray.count)
{
if(itemNumber >= [ intValue] && itemNumber < [ intValue])
{
wallpaperPriceValue = [[ objectForKey:@"value"] floatValue];
check++;
if(check == 2)
{
break ;
}
}
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>我不认为谓词是正确的,最好是枚举对象这里是一些示例代码:</p>
<pre><code>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 = 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);
</code></pre></p>
<p style="font-size: 20px;">关于ios NSPredicate 在 NSDictionary 中查找最接近的值,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/25197307/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/25197307/
</a>
</p>
页:
[1]