计算类中的行并为给定数字选择一行

时间:2015-02-25 17:02:29

标签: ios objective-c mongodb parse-platform database

我正在使用Parse.com创建一个iOS应用程序,我想知道是否有办法检索类中的总行数?例如,我有一个包含100个对象的“MESSAGE”类,有没有办法检索整数,如:

int x = [count MESSAGE]; //现在x = 100;

一旦我的变量x中有100,我会得到1到100之间的随机数,假设函数返回7,有没有办法检索第7行的对象?

1 个答案:

答案 0 :(得分:4)

您可以像这样获取计数:

PFQuery *query = [PFQuery queryWithClassName:@"MESSAGE"];
[query countObjectsInBackgroundWithBlock:^(int count, NSError *error) {
  // count tells you how many objects matched the query
}];

您可以像这样获得第7个对象:

PFQuery *query = [PFQuery queryWithClassName:@"MESSAGE"];
// Skip the first 6, retrieve the next 1
query.skip = 6;
query.limit = 1;
[query findObjectsInBackgroundWithBlock:^(NSArray *messages, NSError *error) {
  // Now you have the 7th MESSAGE at messages[0]
}];

将它们放在一起,你可以这样做:

PFQuery *query = [PFQuery queryWithClassName:@"MESSAGE"];
[query countObjectsInBackgroundWithBlock:^(int count, NSError *error) {
  // Skip the first <random>, retrieve the next 1
  query.skip = arc4random_uniform(count);
  query.limit = 1;
  [query findObjectsInBackgroundWithBlock:^(NSArray *messages, NSError *error) {
    // Now you have a random MESSAGE at messages[0]
  }];
}];