3

我已经使用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];

它被清除了所有的缓存,以便下一次迭代的缓存中没有数据。

4

2 回答 2

9

当使用kPFCachePolicyCacheThenNetwork你的缓存策略时,你的回调总是被触发两次。这是因为策略是先使用缓存上网络,而不是独占使用缓存。

解决方案是跟踪你的块被调用了多少次,这样你就可以确定你是从网络获取缓存的结果还是新的结果。Parse 有更多关于这里的信息。

于 2013-06-10T10:54:43.913 回答
0

您必须清除块 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) 中用于存储从 parse 查询的对象的数据数组。

- (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]);
     }
   }];
}
于 2014-05-26T08:21:42.840 回答