Reputation: 1286
On apple doc, to insert a NSMananagedObject to Core Data, we need to do this :
- (void)insertObject
{
NSMananagedObject *newObject = (UserInfo*)[NSEntityDescription insertNewObjectForEntityForName:@"myEntity" inManagedObjectContext:self.managedObjectContext];
[newObject setValue:@"aName" forKey:@"name"];
NSError *error = nil;
if (![context save:&error]) {
}
}
But if my NSManagedObject is already instanced, how can I do to insert it on Core Data without re-Instancing with 'insertNewObjectForEntityForName:inManagedObjectContext' and copying my attributes ?
I would like something like this :
- (void)insertObject:(NSManagedObject*) newObject
{
//[newObject insertForEntity:@"entityName" forContext:context];
NSError *error = nil;
if (![context save:&error]) {
}
}
Upvotes: 1
Views: 235
Reputation: 25740
An NSManagedObject
can only be created by inserting it into a context. If you really want to have this in a manager class, you need separate functions to create it and then another one to save it. (Well, you can have one that creates & saves, but then you will have to save it again anyway after you modify it.)
I would suggest something like this in your manager class:
- (UserInfo*)createNewUserInfoObject {
return (UserInfo*)[NSEntityDescription insertNewObjectForEntityForName:@"myEntity"
inManagedObjectContext:self.managedObjectContext];
}
- (BOOL)saveUserInfoObjects {
NSError *error = nil;
if (![self.managedObjectContext save:&error]) {
return NO;
}
return YES;
}
Upvotes: 1
Reputation: 2616
You have to subclass your NSManagedObject and validate. That's what they are for is to add custom validations. No need for you to do any extra work and create a manager.
Here is some code to get you started.
- (BOOL) validateForInsert:(NSError *__autoreleasing*)error {
/*! @abstract Validation for Inserting Records */
BOOL bValidity = [super validateForInsert:error];
BOOL bUniqueness = [self validateUniqueness:error];
return ( bValidity && bUniqueness );
}
Note that the super is called first.
Upvotes: 0