Parse.com 查询:缓存始终为空 (iOS)



我正在使用 Parse.com 作为后端编写一个iOS-App。

在我PFQueryTableViewController- (PFQuery)queryForTable方法中,我正在从 Parse 检索一组数据,但我无法缓存此查询以便在设备当前处于脱机状态时支持功能。

该方法如下所示:

- (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]总是返回 false。

在另一个类中,我正在执行几乎完全相同的查询(在不同的 Parse-Class 上),它会自动缓存。唯一的区别是,此其他查询包含PFFiles

这可能是一个愚蠢的问题,但我已经坚持了好几天了。

感谢您的任何帮助,如果我可以为您提供更多信息,请告诉我。

代码使用条件if (self.objects.count == 0)保护缓存策略的设置。似乎您在对象为零时使用缓存,而在查询成功后不使用它。 由于默认设置是不使用缓存,因此代码被安排为从不使用它。

只需删除条件,或在[query hasCachedResult]时有条件地使用缓存

编辑 - 仍然可以/应该无条件地设置缓存策略,但只有在查找后其条件未更改的情况下,查询才能具有hasCachedResults(我在文档中没有看到确认这一点的地方,但它是合理的)。 若要确保查询可以返回缓存的结果,请在查找后保持其条件不变。

[NSDate date] 避免 PFQuery 的缓存。这是一个解决方法:

  1. 不要在视图上查询 NSDate
  2. 但在视图中做确实出现了

代码:

- (PFQuery *)queryForTable {
    PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
    // 1. load from cache only when viewDidLoad        
    // setup query WITHOUT NSDate "where" condition
    if (self.shouldQueryToNetwork) {
        // 2. update objects with date condition only when view appeared
        [query whereKey:@"date" greaterThan:[NSDate date]];
    }
    return query;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.shouldQueryToNetwork = YES;
    // Sync objects with network
    [self loadObjects];
}

相关内容

最新更新