【问题标题】:Randomise and Search Array with NSPredicate使用 NSPredicate 随机化和搜索数组
【发布时间】:2014-07-19 10:28:57
【问题描述】:

我有一个复杂的数组,如下所示:

foodArray = [NSMutableArray arrayWithObjects:
             [Food cat:@"cereals" risk:@"low" name:@"Frosties" image:[UIImage imageNamed:@"frosties.jpg"]],
             [Food cat:@"cereals" risk:@"low" name:@"Coco Pops" image:[UIImage imageNamed:@"cocopops.jpg"]],
             [Food cat:@"cereals" risk:@"low" name:@"Bran Flakes" image:[UIImage imageNamed:@"branflakes.jpg"]],
             [Food cat:@"cereals" risk:@"low" name:@"Golden Crisp" image:[UIImage imageNamed:@"goldencrisp.jpg"]],
             [Food cat:@"cereals" risk:@"low" name:@"Honey Smacks" image:[UIImage imageNamed:@"honeysmacks.jpg"]],
             [Food cat:@"cereals" risk:@"low" name:@"Lucky Charms" image:[UIImage imageNamed:@"luckycharms.jpg"]], nil];

现在我要做的是按“名称”随机化所有项目,然后我想过滤 cat = 谷物和风险 = 低的地方,只选择前 3 种食物。 (稍后将添加更多具有不同猫和风险值的项目)。

我一直在使用以下方法进行随机化:

for (int i = 0; i<[foodArray count]-1; i++)
{
    NSUInteger randomIndex = arc4random() % [foodArray count];

    [foodArray exchangeObjectAtIndex:i withObjectAtIndex:randomIndex];
}

但这意味着我的foodArray,最初是NSArray,已更改为NSMutableArray。现在我该如何过滤数组?我有点坚持这一点,以及如何限制为 3 并搜索数组的两个部分。

编辑

我正在尝试返回 3 种所选食物的名称并使用以下代码:

NSArray *threeFoods=[self getFoodsFromArray:foodArray withRisk:@"low" inCategory:alternativeFood count:3];

    NSString *testText = @"";
    for (NSString *test in threeFoods) {
        testText = [testText stringByAppendingFormat:@"%@\n", test];
    }
    altFood.text = testText;

这在一定程度上可以填充我的文本视图。但是,它以 ' 的形式返回数据

【问题讨论】:

  • 你说的“按'name'随机化”是什么意思?为什么不先过滤数组,将过滤后的数组打乱,然后挑选前 3 个条目?
  • 这可能是更好的方法哈哈!我怎样才能做到这一点?因为我正在过滤“猫”和“风险”

标签: ios objective-c arrays nspredicate


【解决方案1】:

您可以使用此方法过滤数组,然后从数组中返回n随机条目 -

- (NSArray *)getFoodsFromArray:(NSArray*)foodArray withRisk:(NSString *)risk inCategory:(NSString *)cat count:(int)count
{
    NSMutableArray *filteredArray=[[foodArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(risk==%@)and (cat==%@)",risk,cat]] mutableCopy];

    if (count < filteredArray.count) {

        for (int i=0;i<count;i++)
        {
            int randomIndex=arc4random_uniform((int)(filteredArray.count-i));
            [filteredArray exchangeObjectAtIndex:randomIndex withObjectAtIndex:filteredArray.count-i-1];

        }
        [filteredArray removeObjectsInRange:NSMakeRange(0, filteredArray.count-count)];
    }
    return filteredArray;
}

你调用方法如下 -

NSArray *threeFoods=[self getFoodsFromArray:foodArray withRisk:@"low" inCategory:@"cereals" count:3];

您可以按如下方式访问三个食物名称 -

for (Food *food in threeFoods) {
    testText = [testText stringByAppendingFormat:@"%@\n", food.name];
}

【讨论】:

  • 这太棒了,谢谢!只要你多动脑筋。然后,我想从这个数组中返回文本视图中 3 种随机食物的名称。如果你能看一下原帖。我已经对其进行了编辑,以向您展示我当前返回值的问题。谢谢!
  • 您,先生,是救生员!我快到了!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多