นับแถวในคลาสและเลือกแถวสำหรับหมายเลขที่กำหนด

ฉันกำลังสร้างแอป iOS โดยใช้ Parse.com และฉันต้องการทราบว่ามีวิธีดึงจำนวนแถวทั้งหมดในชั้นเรียนหรือไม่ ตัวอย่างเช่น ฉันมีคลาส "MESSAGE" ที่มีวัตถุ 100 รายการ มีวิธีดึงข้อมูลจำนวนเต็มดังกล่าวดังนี้:

int x = [นับข้อความ]; // ตอนนี้ x = 100;

และเมื่อฉันมี 100 ในตัวแปร x ฉันจะได้ตัวเลขสุ่มระหว่าง 1 ถึง 100 สมมติว่าฟังก์ชันคืนค่า 7 มีวิธีเรียกวัตถุในแถวหมายเลข 7 หรือไม่


person iDec    schedule 25.02.2015    source แหล่งที่มา


คำตอบ (1)


คุณสามารถดึงข้อมูลการนับได้ดังนี้:

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]
  }];
}];
person Ian MacDonald    schedule 25.02.2015
comment
ว้าว มันรวดเร็วและเข้าใจง่าย ดูเหมือนจะเป็นความคิดที่ดีทีเดียว ให้ฉันลองดูแล้วฉันจะแจ้งให้คุณทราบ ขอบคุณมากเอียน!! - person iDec; 25.02.2015
comment
คำตอบที่ดี สามารถทำ getFirstObjectInBackgroundWithBlock แทน .limit = 1 ได้ - person danh; 26.02.2015