Parse.com – 如何刷新用户的信息
当我在Parse后端更改例如bool时,我无法在我的iOS应用程序中检索此值。 请参阅以下屏幕截图,其中手动更改了用户对象的第一个bool,并且第二个已从应用程序更改。
第一个不起作用,而一个(从应用程序更改)确实有效。 我正在使用以下代码获取值:
[[PFUser currentUser] objectForKey:@"is_pro"]
在第一种情况下,返回对象始终为nil
(我手动更改了bool)。
在对用户的Parse表进行更改后,请致电
[[PFUser currentUser] fetch]; //synchronous
要么
[[PFUser currentUser] fetchInBackground]; //asynchronous
要么
[[PFUser currentUser] fetchInBackgroundWithBlock:^(PFObject *object, NSError *error) { //asynchronous with completion block
之前
[[PFUser currentUser] objectForKey:@"is_pro"]
获取[PFUser currentUser]
对象的更新副本。
注意: refresh
和refreshInBackgroundWithBlock:
现已弃用,并已替换为fetch
和fetchInBackgroundWithBlock:
更新:
正如Ryan Kreager在评论中指出的那样,使用fetchIfNeeded
, fetchIfNeededInBackground
或fetchIfNeededInBackgroundWithBlock:
可能更好/更有效fetchIfNeededInBackgroundWithBlock:
“因为他们将在可用时使用本地缓存。”
Swift中的示例:
首先,请查看isDataAvailable
和isDirty
。
var user = PFUser.currentUser()! // Gets whether the PFObject has been fetched. // isDataAvailable: true if the PFObject is new or has been fetched or refreshed, otherwise false. user.isDataAvailable() // Gets whether any key-value pair in this object (or its children) has been added/updated/removed and not saved yet. // Returns whether this object has been altered and not saved yet. user.isDirty()
使用fetchIfNeeded
, fetchIfNeededInBackground
或fetchIfNeededInBackgroundWithBlock:
可能更好/更有效fetchIfNeededInBackgroundWithBlock:
“因为它们将在可用时使用本地缓存。”
// Synchronously fetches the PFObject data from the server if isDataAvailable is false. user.fetchIfNeeded() // Fetches the PFObject data asynchronously if isDataAvailable is false, then sets it as a result for the task. user.fetchIfNeededInBackground() // Fetches the PFObject data asynchronously if isDataAvailable is false, then calls the callback block. user.fetchIfNeededInBackgroundWithBlock({ (object: PFObject?, error: NSError?) -> Void in // Code here })
否则,如果不需要使用本地缓存,也可以使用fetch
, fetchInBackground
, fetchInBackgroundWithBlock
。
// Synchronously fetches the PFObject with the current data from the server. user.fetch() // Fetches the PFObject asynchronously and sets it as a result for the task. user.fetchInBackground() // Fetches the PFObject asynchronously and executes the given callback block. user.fetchInBackgroundWithBlock({ (object: PFObject?, error: NSError?) -> Void in // Code here })
当你有指针时,你不能使用fetch。 这是最好的方法:
PFQuery *userQuery = [PFUser query]; [userQuery includeKey:@"addresses"]; [userQuery includeKey:@"cards"]; [userQuery whereKey:@"objectId" equalTo:[PFUser currentUser].objectId]; [userQuery getFirstObjectInBackgroundWithBlock:^(PFObject * _Nullable object, NSError * _Nullable error) { }];