swift解析如何在本地数据存储中保存对象并显示它们?

时间:2015-08-25 12:14:04

标签: swift parse-platform pfquery

我已启用local datastore in app delegate,我已经进行了查询,但如果有no internet,我如何保存这些对象以查看它们?

这是我的问题:

query.findObjectsInBackgroundWithBlock {
         (objects, error) -> Void in
         if error == nil && objects != nil
         {
            self.messages = objects!
            for object in objects! {
               inboxphotos.append(object.objectForKey("photo") as! PFFile)
               inboxusers.append(object.objectForKey("username") as! String) }
          }
}

现在我该如何local query查看此objects

1 个答案:

答案 0 :(得分:4)

在致电findObjectsInBackgroundWithBlock之前,

query.fromLocalDatastore()

这将强制您的查询从localDataStore中提取。您的代码应如下所示:

query.fromLocalDatastore()
query.findObjectsInBackgroundWithBlock {
         (objects, error) -> Void in
         if error == nil && objects != nil
         {
            self.messages = objects!
            for object in objects! {
               inboxphotos.append(object.objectForKey("photo") as! PFFile)
               inboxusers.append(object.objectForKey("username") as! String) }
          }
}

要在本地保存对象,必须先启用localDataStore:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    Parse.enableLocalDatastore()
    Parse.setApplicationId("parseAppId", clientKey: "parseClientKey")
  }
}

使用localDataStore保存对象的推荐方法是使用saveEventually

myObject.saveEventually()

您也可以使用.pinInBackground()将对象保存在localDataStore"永久"中。固定对象可确保在从服务器再次获取本地对象时自动更新它们。它是实现服务器数据脱机缓存的理想方式。