0

I'm quite new with Core Data, and I'm having an issue that I don't understand. I don't know what's going wrong.

I'm saving into my Persistent Store, 7 objects of an entity "Weight" that is read from a JSON file with this code:

for (NSDictionary *values in aWeightValues)
    {
        weightValues = [NSEntityDescription insertNewObjectForEntityForName:@"Weight" 
                                                     inManagedObjectContext:moc];

        [weightValues setValue:[typeWeight objectForKey:@"unit"] forKey:@"unit"];
        [weightValues setValue:[values objectForKey:@"timestamp"] forKey:@"date"];
        [weightValues setValue:[values objectForKey:@"value"] forKey:@"amount"];

        if (![moc save:&error])
        {
            NSLog(@"Problem saving: %@", [error localizedDescription]);
        }
    }

The for loop makes 7 loops, that means it's being saved correctly (speaking about the number of objects).

But then, when I try to retrieve data from the Persistent Store in this way:

-(NSMutableArray *) extractWeightEntities 
{
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    NSError *error;
    NSManagedObjectContext *moc = [appDelegate managedObjectContext];

    NSEntityDescription *entityWeight = [NSEntityDescription entityForName:@"Weight" inManagedObjectContext:moc];
    NSFetchRequest *request = [[[NSFetchRequest alloc]init]autorelease];
    [request setEntity:entityWeight];
    entityWeight = nil;

    fetchResult = [[moc executeFetchRequest:request error:&error]mutableCopy];
    return (fetchResult);

}

and try to show one attribute of each object retrieved, I get 1044 rows in my TableView!! when I should have just 7.

What am I doing wrong? Is the problem when I'm saving, or when I'm retrieving?

I hope you can help to solve this issue. Many thanks in advance!!

4

1 回答 1

1

You don't need to call save on each iteration of the loop, this is very inefficient. Save afterwards.

Put a breakpoint on you loop and ensure it is only going over it 7 times.

Is the data continuously accumulating? Are you deleting the app each time? If you keep running the code - it will keep adding objects to your datastore unless you check if they exist in the datastore before inserting them.

于 2012-01-25T10:52:30.980 回答