0

I have a data base in my app. I use core data. I need to refresh my local data base with information coming from the server. I want to reduce time of updating DB. Let's say i have a table with 3 fields "ID", "Name", "file". In the "file" attribute is saved some large binary data. Here is the code to update my DB.

NSEntityDescription *entity=[NSEntityDescription entityForName:@"Entity" inManagedObjectContext:context];
NSFetchRequest *fetch=[[NSFetchRequest alloc] init];
[fetch setEntity:entity];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"ID == %@", newObject.objectID];
[fetch setPredicate:predicate];
NSError *fetchError;
NSArray *fetchedEntities = [managedObjectContext executeFetchRequest:fetch error:&fetchError];
NSManagedObject *objectToUpdate = [fetchedEntities firstObject];
objectToupdate.name = newObject.name;
BOOL isRecordUpdated = objectToupdate.isUpdated; // returns YES.
NSError *saveError;
[managedObjectContext save:&saveError];

I found a record with ID and changed its name then saved the context. Object is changed and I can be sure it is updated on the server. The question is how does the update work. Will it rewrite the whole record? I mean what happens with the "file" attribute is it also rewritten? If yes, then how to avoid rewriting of large fields that are not changed.

One more case. What if I rewrite the name with a new equal String?

NSString *name = [NSString stringWithFormat:@"%@", objectToUpdate.name];
BOOL nameChanged = firstName != contact.firstName; // returns YES
BOOL nameIsEqual = [firstName isEqualToString:contact.firstName]; //returns YES
objectToUpdate.name = name;
BOOL hasChanges = [NSManagedObjectContext.defaultContext hasChanges]; //returns YES

I didn't change the name content but i changed the name value. If i save the context will it rewrite the Data Base? The aim of this question is to understand how to efficiently work with core data. Should i write custom properties to compare contents of strings, or should i store large data in a distinct table? Thanks for reading so far and sorry for being verbose.

PSsam
  • 639
  • 7
  • 18

1 Answers1

1

I would recommend splitting out properties that don't update frequently, especially if they are large, in to a separate entity that has 1:1 relationship with a parent entity. This has two advantages: 1. when you fetch the parent entity the child entity remains a "fault" if you don't access it and 2. it does not require a database write if you only change a property of the parent entity.

Andy Etheridge
  • 1,283
  • 9
  • 6
  • Thanks for ypur reply. I think it solves half the problem. But what to do with the second part. I use Magical Record to import data from JSON to the local DB and it rewrites all records instead of updating records which are changed. – PSsam Sep 18 '13 at 11:03