ios - Parse 数据库中的随机项

标签 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 个项目。没有结果匹配查询。

最佳答案

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

附注至于为什么 maxIndex 是 19,您正在将 NSNumber 转换为 int。相反,请使用:int maxIndex = [[master objectForKey:@"index"] intValue]。但是,更好的方法还是上面的。

关于ios - Parse 数据库中的随机项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28840766/

相关文章:

android - 使用 Sinch SDK 发送附件

python - 从 Python 的 NLTK 中的自定义文本生成随机句子?

mysql - MySQL 能否生成可以为负数或正数的随机数?

android - 如何从 parse.com (android) 检索更新/更改的数据?

ios - 如何延迟某些行的执行

iphone - UIImage : Resize, 然后裁剪

javascript - 如何获取元素在 UIWebView 中的位置?

iphone - 应用程序仅发出警报,但仍显示角标(Badge)

c++ - 来自具有 std::unordered_multimap 等效键的元素的随机元素

iOS : How to upload an image from a URL to Parse?