设置NSManagedObject的属性后,NSFetchRequest.fetchOffset中断

时间:2013-05-07 15:30:37

标签: objective-c core-data nsfetchrequest

我写了一个从数据库中随机获取记录的方法,但无论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 = @“phonetic”;

日志变为:

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是什么,它总是返回相同的对象。

2 个答案:

答案 0 :(得分:4)

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

您可以尝试将includesPendingChanges设置为NO以获取您的请求。

答案 1 :(得分:0)

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