0
我無法理解如何使用Parse緩存和檢索對象。我試圖創建一個查詢,並緩存對象,然後只檢索緩存的對象,除非用戶保存對象到PFObject,然後我想使用網絡來重新加載數據。iOS/Parse.com - 爲PFQuery創建緩存
這是我的嘗試以及我如何查詢PFObjects。
//Gets the playlists from the desired user
+(void)getPlaylistsForUser:(PFUser *)user withCompletion:(void(^)(NSMutableArray *playlists))completion
{
PFQuery *userQuery = [PFQuery queryWithClassName:@"Playlists"];
userQuery.cachePolicy = kPFCachePolicyCacheElseNetwork;
[userQuery whereKey:@"userId" equalTo:[user objectId]];
[userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error){
NSMutableArray *playlists = [[NSMutableArray alloc]init];
playlists = [objects mutableCopy];
completion(playlists);
}
}];
}
How would I go about notifying the query that there needs to be a network call instead of returning cached results?
編輯:我設法得到所需的功能只有幾行代碼。
//Gets the playlists from the desired user
+(void)getPlaylistsForUser:(PFUser *)user withCompletion:(void(^)(NSMutableArray *playlists))completion
{
PFQuery *userQuery = [PFQuery queryWithClassName:@"Playlists"];
[userQuery whereKey:@"userId" equalTo:[user objectId]];
userQuery.cachePolicy = kPFCachePolicyCacheElseNetwork;
[userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error){
NSMutableArray *playlists = [[NSMutableArray alloc]init];
playlists = [objects mutableCopy];
completion(playlists);
}
}];
}
+ (void)saveTrack:(NSDictionary *)track toPlaylist:(PFObject *)playlist withCompletion:(void(^)(BOOL success))completion
{
[playlist addObject:track forKey:@"playlist"];
[playlist saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error)
{
NSLog(@"Error creating/saving playlist");
}
else{
PFUser *current = [PFUser currentUser];
PFQuery *playlistQuery = [PFQuery queryWithClassName:@"Playlists"];
[playlistQuery whereKey:@"userId" equalTo:[current objectId]];
[playlistQuery clearCachedResult];
completion((BOOL)YES);
}
}];
}
本質上,我只是在我需要查詢重新加載數據時清除特定查詢的緩存結果。我設置查詢的cachePolicy爲kPFCachePolicyCacheElseNetwork
這是緩存的最佳方式嗎?似乎按預期工作。
謝謝你,這是有道理的。爲什麼xcode不允許我寫這行 query.cachePolicy = self.cachePolicy; 所有這些代碼都在我正在寫的API中。 – Andy
嗯。確保你已經聲明* not *作爲指針。 – danh