Parse数据库中的随机项

时间:2015-03-03 19:53:27

标签: ios random parse-platform

我想从我的数据库中获取一个随机对象,但它不起作用。

这就是我的数据库的样子:

PFObject *master = [[PFQuery queryWithClassName:@"items"] getFirstObject];
int maxIndex = [master objectForKey:@"index"];

NSLog(@"MaxIndex = %d", maxIndex);

// Randomly pick an index in the range maxIndex.
int randomIndex = arc4random() % maxIndex;

// Get the card with that particular index.
PFQuery *cardQuery = [PFQuery queryWithClassName:@"items"];
[cardQuery whereKey:@"index" equalTo:[NSNumber numberWithInt:randomIndex]];
PFObject *card = [cardQuery getFirstObject];

NSLog(@"The next item is picked: %@", card);
label.text = card;

问题是什么? 问题是它输出maxIndex为19,即使数据库中只有2个项目。并且没有与查询匹配的结果。

2 个答案:

答案 0 :(得分:1)

getFirstObject每次都返回第一个(和相同的)项目。这可能导致您的maxIndex每次都设置为1。这意味着您的randomIndex也将为1,每次都会为您提供相同的卡片。

尝试使用countObjectsInBackgroundWithBlock:作为第一个查询,然后选择一个小于计数的随机数,最后检索随机项。

以下内容,但请务必妥善处理错误:

PFQuery *countQuery = [PFQuery queryWithClassName:@"items"];
[countQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
    int randomIndex = arc4random() % number;

    // Get the card with that particular index.
    PFQuery *cardQuery = [PFQuery queryWithClassName:@"items"];
    [cardQuery whereKey:@"index" equalTo:[NSNumber numberWithInt:randomIndex]];
    [cardQuery getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
        NSLog(@"The next item is picked: %@", object);
    }];
}];

P.S。至于为什么你的maxIndex是19,你将NSNumber转换为int。相反,请使用:int maxIndex = [[master objectForKey:@"index"] intValue]。但是,更好的方法是上面。

答案 1 :(得分:0)

退出派对迟到了。但是这里有一个快速的4通用版本来获取随机对象。

  1. 计算对象
  2. 获取随机索引
  3. 创建新查询
  4. 设置跳到值
  5. 添加限制1并返回

    extension PFQuery where PFGenericObject == PFObject { func getRandomObject(callback: @escaping (PFObject?) -> Void) { let className = parseClassName countObjectsInBackground { (number, error) in let newQuery = PFQuery(className: className) let randomIndex = Int(arc4random() % UInt32(number)) newQuery.skip = randomIndex newQuery.limit = 1 newQuery.findObjectsInBackground(block: { (objects, error) in callback(objects?.first) }) } } }