使用NSPredicate的随​​机和搜索数组

时间:2014-07-19 10:28:58

标签: ios objective-c arrays nspredicate

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

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种食物。 (稍后将添加更多项目,具有不同的cat和风险值)。

我一直在随机使用以下内容:

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;

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

1 个答案:

答案 0 :(得分:2)

您可以使用此方法过滤数组,然后从数组中返回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];
}