user1027410
user1027410

Reputation: 1

Objective-C => Can't update existing objects in CoreData

I can't update objects in my database using core data, this my function :

- (void) saveItem:(NSDictionary*)dico {

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Item" 
        inManagedObjectContext:managedObjectContext];
    Item *item =(Item *)[entity ReadSingleForKey:@"identifier"
                                           value:[dico valueForKey:@"identifier"]
                                       inContext:managedObjectContext];
    if (!item) {
        item = [[[NSManagedObject alloc] initWithEntity:entity
            insertIntoManagedObjectContext:managedObjectContext] autorelease];
        item.identifier = [dico valueForKey:@"identifier"];
    }
    item.title = [dico valueForKey:@"title"];
    NSError *error = nil;
    if (![managedObjectContext save:&error])
    {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }else{
        NSLog(@"No error found.");
    }
}

Even if "item" is not nil the object in the database doesn't change & I got always "No error found.".

- (NSManagedObject *) ReadSingleForKey:(NSString *) key 
        value:(id) value inContext:(NSManagedObjectContext *) context{

    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    [request setEntity:self];

    [request setPredicate:[NSPredicate predicateWithFormat:@"%K = %@", key, value]];
    [request setFetchLimit:1];

    NSError *error;
    NSArray *arr = [context executeFetchRequest:request error:&error];
    if (arr && [arr count]) {
        return [arr objectAtIndex:0];
    }
    return nil;
}

Any idea ??

Upvotes: 0

Views: 303

Answers (2)

user1027410
user1027410

Reputation: 1

The problem was in my Item class :

I was using @synthesize instead of @dynamic

Upvotes: 0

Mundi
Mundi

Reputation: 80271

There are several problems with your code that make it difficult to determine the error.

1) No error handling.
2) Obscure private method ReadSingleForKey - what does it return?
3) item defined as type Item and as different type NSManagedObject in same method.

Put in NSLog statements or breakpoints to examine the values of dico and item. You will soon find the place where you go wrong.

Another potential source of this error is how you read the data from the database later. For now I am assuming that this is working correctly.

Upvotes: 3

Related Questions