Ios 使用NSPredicate随机化和搜索数组

Ios 使用NSPredicate随机化和搜索数组,ios,objective-c,arrays,nspredicate,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 i

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

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];
}

这在一定程度上可以填充我的文本视图。但是,它以“的形式返回数据。您可以使用此方法筛选数组,然后从数组中返回
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;
}
您可以访问以下三种食物名称-

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

可能重复您所说的“按‘名称’随机分组”是什么意思?你为什么不先过滤数组,洗牌过滤后的数组,然后选择前3个条目?这可能是一个更好的方法哈哈!我该怎么做?因为我正在过滤“猫”和“风险”,这太棒了,谢谢!只要你再多动脑筋。从这个数组中,我想返回textview中3种随机食物的名称。如果你能看看原来的帖子。我对其进行了编辑,以向您显示我当前返回值的问题。谢谢先生,你是救命恩人!我就快到了!非常感谢!
NSArray *threeFoods=[self getFoodsFromArray:foodArray withRisk:@"low" inCategory:@"cereals" count:3];
for (Food *food in threeFoods) {
    testText = [testText stringByAppendingFormat:@"%@\n", food.name];
}