Reputation: 701
I am a VERY new beginner to Core Data and I have recently been trying to read and write data. I created an entity named "Person" with the entities "name" and "age". I also have a textfield name "personName" and a textfield named "personAge".
- (IBAction)readData:(id)sender
{
NSNumber *ageNum = [NSNumber numberWithInteger:personAge.text.integerValue];
Person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext];
newPerson.name = personName.text;
newPerson.age = ageNum;
NSLog(@"Person %@ name is %@", personName.text, ageNum);
}
When I load the app, all i get is SIGABRT. Even when all I put in the method is
Person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext];
All help is appreciated.
Upvotes: 0
Views: 724
Reputation: 3082
For Adding values to the core data you can do so:-
- (IBAction)save:(id)sender {
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new managed object
NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
[person setValue:self.personName.text forKey:@"name"];
[person setValue:self.personAge.text forKey:@"age"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
}
For fetching the values from core data:-
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Person"];
self.personValues = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
here personValues is a NSMutableArray. For better understanding about these please go through this link.
http://www.appcoda.com/introduction-to-core-data/
Hope this will help you out.
Upvotes: 1
Reputation: 854
If you are very new to Core Data, try using the MagicalRecord library which provides a series of helper categories for dealing with a lot of the boiler plate setup of Core Data.
Which brings me to the question you are asking: are you sure your Core Data stack is being setup correctly? Check to make sure your Managed Object Context is valid along with a proper Persistent Store Coordinator.
Best thing to do: put a breakpoint during the Core Data stack setup and step through it making sure everything is setup properly. Or install MagicalRecord and do one method call to [MagicalRecord setupAutomigratingCoreDataStack]...
Upvotes: 0