Coredata entity with exactly one row

One of my coredata tables (uh, entities) should have ever only one row of data being stored. When the row doesn't exist yet it should be created and if it already exists, the same row should be overwritten (or edited) with new data.

Currently in my implementation a new row is always added to the entity (named 'TempNames'):

/* Store names data in temporary name table. */
TempNames *tempNames = [NSEntityDescription insertNewObjectForEntityForName:@"TempNames" inManagedObjectContext:context];
tempNames.namesData = tempNamesData;

Can anyone give me some hints what is needed to change it to my desired functionality? I suppose NSPredicate is required to achieve what I want?


UPDATED WORKING IMPLEMENTATION:

/* Convert names array into serializable data. */
NSData *tempNamesData = [NSKeyedArchiver archivedDataWithRootObject:names];

/* Store names data in temporary name table. */
TempNames *tempNames = nil;
NSError *error;
NSFetchRequest *req = [NSFetchRequest fetchRequestWithEntityName:@"TempNames"];
NSArray *records = [context executeFetchRequest:req error:&error];

/* Record already exists. */
if (records.count > 0)
{
    tempNames = records.firstObject;
}
else
{
    tempNames = [NSEntityDescription insertNewObjectForEntityForName:@"TempNames" inManagedObjectContext:context];
}
tempNames.namesData = tempNamesData;

[context save:&error];

Answers


If you insert a new entity every time, you are not doing an insert/update operation, it's always an insert operation, even if the data of that entity is the same. What you should do is first fetch if you have that data in your store and then decide if you need to insert or update it.

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"TempNames"];
NSError *error;
NSArray *entities = [context executeFetchRequest:request error:&error];
if (entities.count > 0) {
    // You have already inserted the entity
}
else {
    // Insert your new entity
    ...
    // Save changes to the store
    NSError *error;
    [context save:&error];
}

Try it like this:

TempNames *tempNames = nil;
NSFetchRequest *appRequest = [NSFetchRequest fetchRequestWithEntityName:@"TempNames"];
    NSArray *allNames = [context executeFetchRequest:appRequest error:nil];

if (allNames.count > 0) {
   // your record exists
   tempNames = allNames.firstObject;
} else {
     tempNames = [NSEntityDescription insertNewObjectForEntityForName:@"TempNames" inManagedObjectContext:context];
}
tempNames.namesData = tempNamesData;

Need Your Help

ExtJS4: how can i check if Shift+Enter is pressed on a textarea

javascript javascript-events extjs extjs4

I want to submit the form if Enter is pressed and stop the event if Shift + Enter is pressed. The callback for this has Ext.EventObject parameter which does not provide any way to check if shiftkey...