我想从我的数据库中随机获取一个对象,但它不起作用。
这是我的数据库的样子:
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/