解析:检索最后一个对象

时间:2015-09-17 19:58:38

标签: ios swift parse-platform

我试图通过desc字段“createdAt”检索选择订单的最后一个对象: 在SQL中是这样的:

var app = express();
app.use(morgan('dev'));
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));

我试试这个,但不起作用。结果是第一个对象:

SELECT *   
FROM Message
ORDER BY createdAt DESC
LIMIT 1

使用这个懒惰的代码,我得到我想要的东西,但我必须循环所有对象:

let query = PFQuery(className: "Message")

query.orderByDescending("createdAt")
query.limit = 1

var lastMessage = "..."

if let objects = query.findObjects() as [AnyObject]?
{
    for object in objects
    {
        //Execute one time only and don't return the row that i want
        lastMessage = object["Text"] as! String
    }
}

2 个答案:

答案 0 :(得分:0)

var lastMessage = "..."        

let query = PFQuery(className: "Message", predicate: predicate)

query.orderByDescending("createdAt")

if let object = query.getFirstObject() as PFObject?
{
    lastMessage = object["Text"] as! String
}

答案 1 :(得分:0)

不惜一切代价避免使用findObjects()等同步调用。相反,请尝试使用findObjectsInBackgroundWithBlock

let query = PFQuery(className: "Message")
query.orderByDescending("createdAt")
query.limit = 1
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
    if (error == nil) {
        if let firstObject = objects?.first {
            lastMessage = firstObject["Text"] as! String
        }
    } else {        
        // Log details of the failure
        println("query error: \(error) \(error!.userInfo!)")
    }
}