I'm writing an iOS-App using Parse.com as a backend.
In the - (PFQuery)queryForTable
method of my PFQueryTableViewController
I'm retrieving a set of data from Parse, but I'm unable to cache this query in order to support functionality when the device is currently offline.
The method looks as followed:
- (PFQuery *)queryForTable {
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
[query whereKey:@"city" equalTo:[[NSUserDefaults standardUserDefaults] objectForKey:@"city"]];
// userMode is active when a user is logged in and is about to edit coins
if (self.userModeActive) {
[query whereKey:self.textKey equalTo:self.user[@"location"]];
}
// dateFilter is active when view is pushed from an event
if (self.dateFilterActive) {
[self createDateRangeForFilter];
[query whereKey:@"date" greaterThan:[[self createDateRangeForFilter] objectAtIndex:0]];
[query whereKey:@"date" lessThan:[[self createDateRangeForFilter] objectAtIndex:1]];
} else {
// Add a negative time interval to take care of coins when it's after midnight
[query whereKey:@"date" greaterThanOrEqualTo:[[NSDate date] dateByAddingTimeInterval:-(60 * 60 * 6)]];
[query orderByAscending:self.dateKey];
}
// locationFilter is active when view is pushed from a location profile
if (self.locationFilterActive) {
[query whereKey:@"location" equalTo:self.locationToFilter];
}
// If no objects are loaded in memory, look to the cache first to fill the table
// and then subsequently do a query against the network.
if (self.objects.count == 0) {
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
}
if ([query hasCachedResult]) {
NSLog(@"hasCache");
} else {
NSLog(@"chache empty");
}
return query;
}
[query hasCachedResults]
always returns false in this case.
In another class, I'm doing the almost exactly same query (on a different Parse-Class) and it caches automatically. The only difference is, that this other query contains PFFiles
.
This may be a dumb question but I'm stuck with it for days now.
Thanks for any help and let me know if I can give you more information.
The [NSDate date] avoid the cache of PFQuery. Here is a work-around:
The code:
The code guards the setting of cache policy with a conditional
if (self.objects.count == 0)
. It would seem that you're using the cache when there are zero objects and not using it after the query has succeeded. Since the default is to not use the cache, the code is arranged to never use it.Just remove the conditional, or use the cache conditionally upon
[query hasCachedResult]
EDIT - It is still the case that the cache policy can/should be set unconditionally, but a query can have hasCachedResults only if its criteria don't change after the find (I don't see a place in the docs confirming this, but it stands to reason). To insure that a query can return cached results, leave its criteria unchanged after the find.