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

Parse.com Query: Cache is always empty (iOS)

我正在编写一个 iOS-应用程序,使用 Parse.com 作为后端。

在我 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] 在这种情况下总是 returns false。

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

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

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

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

只需删除条件,或根据[query hasCachedResult]

有条件地使用缓存

EDIT - 无条件设置缓存策略 can/should 仍然是这种情况,但只有当查询条件在之后不更改时,查询才能具有 hasCachedResults发现(我在文档中没有看到证实这一点的地方,但这是有道理的)。为确保查询可以 return 缓存结果,请在查找后保持其条件不变。

[NSDate日期]避开PFQuery的缓存。这是一个解决方法:

  1. 不在 viewDidLoad 查询 NSDate
  2. 但在 viewDidAppear 中进行

代码:

- (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];
}