We will begin this tutorial by defining some of the concepts that are required to use Core Data model before providing an overview of the steps involved in working with this framework. Later we learn how to save and retrieved data from database.
1. Create a Database for Coredata
Go to file-> New File -> iOS -> Coredata -> Datamodel and create a database with name “CoreData”
Now it’s time to create table in it, to create a table click on add entity button as shown in fig by red circle.
To add attributes in it click on ‘+’ button, it will add an attribute in list.
As in our case we have created a table with name “TableName” and two attributes column1 and column2.
Now we create the class object of this table, to do the same go to
File -> New file -> Coredata -> NSManagedObjectSubClass and follow below steps
Now select your created database here and press next,
After clicking on Next button you will see all the tables associated with selected database, select desired table to convert in class object from here,
(You can select multiple table together)
Congratulation now you have all the ingredients required for database operation.
2. Database Method
First of all create some properties for it in app delete
@property (readonly, strong, nonatomic)
NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic)
NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic)
NSPersistentStoreCoordinator
*persistentStoreCoordinator;
Make sure you have synthesized them before use.
Below are the frameworks, which we need to use coredata. Add them in your link library first.
Now write the following methods in your AppDelegate.m
For more details visit here
#pragma mark – Core Data
// Returns the managed object context for the application.
// If the context doesn’t already exist, it is created and bound to the persistent store coordinator for the application.
– (NSManagedObjectContext *)managedObjectContext
{
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn’t already exist, it is created from the application’s model.
– (NSManagedObjectModel *)managedObjectModel
{
if (managedObjectModel != nil) {
return managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@”CoreData” withExtension:@”momd”];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel;
}
// Returns the for the application.
// If the coordinator doesn’t already exist, it is created and the application’s store added to it.
– (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@”CoreData.sqlite”];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);
abort();
}
return persistentStoreCoordinator;
}
// Returns the URL to the application’s Documents directory.
– (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
3. Method to save data
In our example we have a database with name “Coredata”, a table with name “TableName” and two attributes “column1” and “column2”.
// Here appDelegate is the class object of applications AppDelegate
NSManagedObjectContext* context = [appDelegate managedObjectContext];
TableName* tableObject = [NSEntityDescription insertNewObjectForEntityForName:@”TableName” inManagedObjectContext:context];
tableObject.column1 = @”give your value here for column1″;
tableObject.column2 = @”give your value here for column2″;
NSError* error;
BOOL isSaved = [context save:&error];
if(isSaved==NO || error!=nil) {
NSLog(@”Data saving Error: %@”,error.debugDescription);
} else {
NSLog(@”Data saved”);
}
This will save the data in database.
4. Method to retrieve data
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *tableEntity = [NSEntityDescription entityForName:@”TableName” inManagedObjectContext:context];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
fetchRequest.returnsObjectsAsFaults = NO;
[fetchRequest setEntity: tableEntity];
NSError* error = nil;
NSArray* logArray = [context executeFetchRequest:fetchRequest error:&error];
if(sortedArray!=nil) {
TableName* tableObject = [sortedArray objectAtIndex:0];
NSLog(@” column 1 value = %@ , Column 2 value = %@”, tableObject.column1, tableObject.column2);
}
}
Related Posts...
GeneralMobile AppsTechnologies
Dec 17th, 2024
Planning a holiday can be both exciting and overwhelming. With so many details to organise – from booking flights to reserving hotels and planning itineraries – having the right travel […]
Read more
Dec 12th, 2024
Technology is advancing at an unprecedented pace, reshaping industries and redefining the roles of professionals. As we approach 2025, staying ahead of the curve requires understanding emerging trends and their […]
Read more
Dec 10th, 2024
As 2024 comes to a close, it’s the perfect time to reflect on the remarkable technological innovations that have shaped the year. From advancements in Artificial Intelligence (AI) to the […]
Read more