I need to check if there any nil
values in my managedObjectContext
before saving them. At the minute I am doing tests on each key using if
statements. I have many attributes in my NGLS
entity, so as you can see testing each key for nil
values doesn't seem very practical.
if ([_managedObjectNGLS valueForKey:@"q1"] == nil){
[_managedObjectNGLS setValue:@"" forKey:@"q1"];
}
if ([_managedObjectNGLS valueForKey:@"q1More"] == nil){
[_managedObjectNGLS setValue:@"" forKey:@"q1More"];
}
....
// Save managedObject
NSError *error;
[[self.managedObjectNGLS managedObjectContext] save:&error];
NSLog(@"%@", self.managedObjectNGLS);
NSLog(@"Data saved");
Often there are many nil
values, which I need to change manually with many if statements
. Is there a way to batch test all objects in my entity for nil values? And if so, is there a way to replace all of these with a set string
at once? Thanks.
Core Data includes powerful capabilities for validation. As part of a save, Core Data validates object properties, ensuring that only valid object are persisted.
You can implement validation rules in the Core Data Model Editor, or yourself in code by implementing key-value validation on your managed object subclass.
For example, using the model editor you can set a property to be non-optional and provide a default value: