2015-08-25 24 views
2

我已啓用local datastore in app delegate,我已經做了一個查詢,但我如何保存該對象來查看它們,如果有no internetswift解析如何保存本地數據存儲中的對象並顯示它們?

這裏是我的查詢:

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

+0

你可以調用'saveInBackgroundWithBlock'方法給PFObject把它保存到本地數據庫,記得本地數據庫必須在AppDelegate中啓用。 爲了檢索數據,創建PFQuery對象並調用'findObjectsInBackgroundWithBlock'方法。 – Suryakant

+0

@SuryakantSharma我應該何時調用saveInBackgroundWithBlock?在findObjectsInBackgroundWithBlock裏面還是什麼時候? – Salah

+1

不! 'findObjectsInBackgroundWithBlock'用於從Parse DB使用'PFQuery'獲取對象,'saveInBackgroundWithBlock'用於保存。 – Suryakant

回答

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中。固定對象可確保當您從服務器再次獲取本地對象時,本地對象會自動更新。這是實現服務器數據的離線緩存的理想方式。

+0

謝謝你,我做到了,但我沒有得到任何結果,因爲本地數據存儲是空的,你能編輯你的答案,並做如何將對象保存在本地數據存儲? – Salah

相關問題