0

我写了一个从数据库中随机获取记录的方法,但是不管 NSFetchRequest.fetchOffset 是什么,我经常得到相同的记录。

所以我做了一个实验,这是我的代码:

- (Card *)getNextCard {
    Card *card = nil;
    while (YES) {
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Card"];
        request.fetchLimit = 1;
        request.fetchOffset = arc4random_uniform(1031);

        NSError *error = nil;
        NSArray *matches = [self.database.managedObjectContext executeFetchRequest:request error:&error];

        if (matches) {
            card = [matches lastObject];
            // card.phEn= @"phonetic";
        }
        NSLog(@"nextCard: %@, %d", card ? card.en : card, request.fetchOffset);
    }
    return card;
}

使用上面的代码,日志是这样的:

2013-05-07 23:11:16.035 MyApp[20598:707] nextCard: astound, 153
2013-05-07 23:11:17.175 MyApp[20598:707] nextCard: complicate, 370
2013-05-07 23:11:18.335 MyApp[20598:707] nextCard: hasten, 954
2013-05-07 23:11:19.801 MyApp[20598:707] nextCard: exonerate, 749
2013-05-07 23:11:23.159 MyApp[20598:707] nextCard: exalted, 736
2013-05-07 23:11:24.389 MyApp[20598:707] nextCard: Leninism, 3
2013-05-07 23:11:25.749 MyApp[20598:707] nextCard: commotion, 360
2013-05-07 23:11:27.959 MyApp[20598:707] nextCard: discern, 565
2013-05-07 23:11:28.895 MyApp[20598:707] nextCard: aluminum, 85

这很好。

但是当我取消注释这一行时:

// card.phEn= @"语音";

日志变成:

2013-05-07 23:25:02.183 MyApp[20645:707] nextCard: annex, 104
2013-05-07 23:25:04.042 MyApp[20645:707] nextCard: annex, 614
2013-05-07 23:25:06.095 MyApp[20645:707] nextCard: annex, 926
2013-05-07 23:25:07.393 MyApp[20645:707] nextCard: annex, 628
2013-05-07 23:25:08.968 MyApp[20645:707] nextCard: annex, 809
2013-05-07 23:25:10.316 MyApp[20645:707] nextCard: annex, 265
2013-05-07 23:25:11.534 MyApp[20645:707] nextCard: annex, 762

似乎无论 fetchOffset 是什么,它总是返回相同的对象。

4

2 回答 2

5

这可能是由于您的上下文未保存(待处理)已更改。不幸的是,这并没有很好的记录。

您可以尝试设置includesPendingChangesNO您的要求。

于 2013-05-07T15:38:13.643 回答
0

当您调用该getNextCard方法时,您的商店是否已经填充了 Card 对象?如果是这样,您确定它返回相同的对象吗?也许您应该尝试 NSLog Card 对象的 objectID。

于 2013-05-07T15:41:00.217 回答