How to loop through nsfetchedresultcontroller

in my application I need a loop through all my objects in Core Data, and I use NSFetchedresultcontroller.

I do it like this:

NSArray *tempArray = [[NSArray alloc] initWithArray:self.fetchedResultsController.fetchedObjects];

for (MyClass *item in tempArray)
{
    // do something
}

[tempArray release]; tempArray = nil;

Is there a better way to do this without creating a tempArray?

Thank you so much

+5
source share
2 answers

Depends on what you want to do. If you just change the value, then yes, there is an easier way:

[[[self fetchedResultsController] fetchedObjects] setValue:someValue forKey:@"someKey"]

which will go through all the objects that set the value. This is a standard KVC operation. Note that this will expand memory, as each object will be implemented during mutation.

- , . . . , Core Data, .

, . , , reset , . , , , , . :

NSManagedObjectContext *moc = ...;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSInteger drainCounter = 0;
for (id object in [[self fetchedResultsController] fetchedObjects]) {
  //Do your magic here
  ++drainCounter;
  if (drainCounter = 100) {
    BOOL success = [moc save:&error];
    NSError *error = nil;
    NSAssert2(!success && error, @"Error saving moc: %@\n%@", [error localizedDescription], [error userInfo]);
    [moc reset];
    [pool drain], pool = nil;
    pool = [[NSAutoreleasePool alloc] init];
    drainCounter = 0;
  }
}

BOOL success = [moc save:&error];
NSError *error = nil;
NSAssert2(!success && error, @"Error saving moc: %@\n%@", [error localizedDescription], [error userInfo]);
[pool drain], pool = nil;

, !. 100 . , , .

+11

, , :

        for (MyClass *item in self.fetchedResultsController.fetchedObjects)
        {
            //do something
        }

?

+6

All Articles