Search code examples
objective-ccore-datasequential

Objective-C Core Data sequential read loop


I need to cycle through a core data database from front to back and it seems that the only alternatives I have are to 1) load the entire database into an array with a single fetch or 2) use keys to increment my way through the database object by object.

I simply don't see something like 'read next' anywhere in the docs. I can do #2 with some effort but it seems silly. Please tell me I'm missing something which is hopefully very obvious.

solution code....

I put up some code fragments as requested by one of the posters below:

fetchedObjects = nil;
fetchedObjects = [[NSMutableArray alloc] init];
localxmlBlock = [[NSData alloc] init];

savedFetchOffset = 0;
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Item"  inManagedObjectContext: localFindItDataController.managedObjectContext];
[fetch setEntity:entityDescription];
[fetch setFetchLimit:1];
[fetch setFetchOffset:savedFetchOffset];

NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"itemAttribute1" ascending:YES];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"itemUniqueID" ascending:YES];
[fetch setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor1, sortDescriptor2, nil]];

nsarrayFetchedObjects = [localFindItDataController.managedObjectContext executeFetchRequest:fetch error:&error];

if ([nsarrayFetchedObjects count] != 0) {


    do {

        do a whole great big bunch of stuff

       savedFetchOffset++;
        [fetch setFetchOffset:savedFetchOffset];
        nsarrayFetchedObjects = [localFindItDataController.managedObjectContext executeFetchRequest:fetch error:&error];

    } while ([nsarrayFetchedObjects count] != 0);}

not the greatest code ever written but does give a flavor of how this seems to work


Solution

  • I think the closest to what you are looking for is fetchOffset, together with fetchLimit and perhaps fetchBatchSize. These are described in the Apple Docs here.

    I should just mention that it is likely to be very inefficient to fetch each object one by one - fetching in larger batches/all at once might be better in spite of the memory overhead.