I have a relatively simple core data sqlite database. I am trying to get results from DB one page at a time.
NSFetchRequest* request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[...]];
[request setPredicate:[NSPredicate predicateWithFormat:@"flaggedTime != nil"]];
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"flaggedTime" ascending:NO];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[request setFetchLimit:pageSize];
[request setFetchOffset:((pageIndex - 1) * pageSize)];
NSArray* results = [self.context executeFetchRequest:request error:NULL];
pageSize is 30, pageIndex on testing data is 1, 2, 3 or 4 (there are about 80 items in DB, so pageIndex = 4 should return no items).
Predicate and sorting works fine, results are successfully returned. Fetch limit works fine, too. No errors are returned.
Problem: I always get results from the first page, as if fetchOffset was not set. I tried to remove the predicate and the sorting but to no avail.
The only situation when I could make fetchOffset work was when I used values under 30. Of course, that is meaningless for paging...
Does anybody know why? I will be really thankful for every answer.
Update: I am speaking about iOS. Tested on 4.2 and 5.0.
Update 2: To simplify the problem.
NSFetchRequest* request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[...];
NSError* error = nil;
NSManagedObjectContext* context = [...];
NSUInteger count = [context countForFetchRequest:request error:&error];
assert(error == nil);
NSLog(@"Total count: %u", count);
request.fetchOffset = 0;
request.fetchLimit = 30;
NSLog(@"Fetch offset: %u, limit: %u", request.fetchOffset, request.fetchLimit);
NSArray* page1 = [context executeFetchRequest:request error:&error];
assert(error == nil);
NSLog(@"Page 1 count: %u", page1.count);
request.fetchOffset = 30;
request.fetchLimit = 30;
NSLog(@"Fetch offset: %u, limit: %u", request.fetchOffset, request.fetchLimit);
NSArray* page2 = [context executeFetchRequest:request error:&error];
assert(error == nil);
NSLog(@"Page 2 count: %u", page2.count);
gives:
Total count: 34
Fetch offset: 0, limit: 30
Page 1 count: 30
Fetch offset: 30, limit: 30
Page 2 count: 30 (ERROR: should give 4)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…