我需要在同一个解析查询中做两件事。 1)我需要找到给定查询返回的对象总数; 2) 仅显示前 20 个对象。我无法通过设置 query.limit = 20
来同时执行这两项操作,因为对象总数仅为 20。如果对象总数为 100,我需要获取该数字。
那么,如何才能以编程方式仅显示前 20 个对象,同时仍接收全部 100 个对象?
var query = PFQuery(className: "Professions")
query.whereKey("user", equalTo: PFUser.currentUser()!.username!)
query.orderByDescending("createdAt")
// query.limit = 20
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
// I tried using something like:
// for var i = 0; i <= 20; i++ {
// if object[i] {
// But get 'Int' is not convertible to 'String'
if let title = object["title"] as? String {
println(title)
}
}
}
} else {
println(error)
}
})
当我尝试设置以下内容时,我总是收到 fatal error :数组索引超出范围。
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
最佳答案
也许不是最优雅的解决方案,但我认为您需要对同一个查询执行两个查询。一种用于 object.count
,另一种用于 query.limit
。
var query = PFQuery(className: "Professions")
query.whereKey("user", equalTo: PFUser.currentUser()!.username!)
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
var numberOfObjects = objecs.count
}
else {
println(error)
}
query.limit = 20
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
if let title = object["title"] as? String {
println(title)
}
}
}
else {
println(error)
}
}
})
关于ios - 在 Swift 中限制没有 query.limit 的解析查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30922795/