我使用 Parse.com构建 iOS 应用
我想首先从缓存检索数据& 然后从网络
为此,我使用了 kPFCachePolicyCacheThenNetwork
缓存政策,选择我的要求。
PFQuery *employesquery = [PFQuery queryWithClassName:@"employesTable"];
[employesquery whereKey:@"UserID" equalTo:[PFUser currentUser]];
[employesquery includeKey:@"empID"];
[employesquery includeKey:@"empID.user"];
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
//APPLIES CACHE... ********
employesquery.cachePolicy = kPFCachePolicyCacheThenNetwork;
[employesquery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
[hud hide:YES];
NSMutableArray *empData = [[NSMutableArray alloc] init];
for (PFObject *object in objects)
{
//Getting Data For Item
PFObject *employeeObject = [object objectForKey:@"empID"];
[empData addObject:employeeObject];
}
[self fetchEmployeeData:empData];
}];
但使用此每个数据检索两次,可重复的数据。
如何避免此可重复数据,
数据从网络获取后,先前显示的数据(使用缓存)将被清除/隐藏。
我尝试了[PFQuery clearAllCachedResults];
清除了所有缓存,以便缓存中没有数据用于下一次迭代。
答案 0 :(得分:9)
使用kPFCachePolicyCacheThenNetwork
作为缓存策略时,您的回调始终会被触发两次。这是因为策略是使用缓存然后转到网络,而不是专门使用缓存。
解决方案是跟踪您的块被调用的次数,这样您就可以确定是从网络获取缓存结果还是新结果。 Parse有more information about this here。
答案 1 :(得分:0)
您必须清除用于在块findObjectsInBackgroundWithBlock中解析的存储对象的数据数组:^(NSArray * objects,NSError * error)。
- (void)refreshData
{
PFUser *currentUser = [PFUser currentUser];
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ = '%@' OR %@ = '%@'",
kMessageUserSendIdKey, currentUser.objectId,
kMessageUserReceiveIdKey, currentUser.objectId]];
PFQuery *query = [PFQuery queryWithClassName:kMessageClassKey predicate:predicate];
[query addDescendingOrder:kMessageTimeCreatedKey];
[query includeKey:kMessageUserSendKey];
[query includeKey:kMessageUserReceiveKey];
[query setCachePolicy:kPFCachePolicyCacheThenNetwork];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// TODO: Clear the data array
self.messagesDataArray = [NSMutableArray new];
if (objects.count > 0) {
[self.messagesDataArray addObject:objects[0]];
for (int i = 1; i < objects.count; i++) {
PFObject *messageChat = [objects objectAtIndex:i];
if (![self isExistWithMessageChat:messageChat]){
[self.messagesDataArray addObject:messageChat];
}
}
[self.tableView reloadData];
}
}
else {
NSLog(@"Error: %@ %@", error, [error userInfo]);
}
}];
}