Coredata add in Existing project

ViewController.h

#import <UIKit/UIKit.h>

#import “CoreDataUtility.h”

#import “Form.h”

#import “Utility.h”

@interface ViewController : UIViewController

– (IBAction)buttonActionInsertData:(id)sender;

– (IBAction)buttonActionFetchData:(id)sender;

– (IBAction)buttonActionUpdataData:(id)sender;

– (IBAction)buttonActionDeleteData:(id)sender;

– (IBAction)buttonActionViewAllData:(id)sender;

– (IBAction)buttonActionDeleteAllData:(id)sender;

@end

ViewController.m

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

– (IBAction)buttonActionInsertData:(id)sender {

    

    {

    NSMutableDictionary *dictionaryStudentDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                    @”Philippe”, @”firstName”,

                                                    @”Wilson”, @”lastName”,

                                                    @”1212121212″, @”phoneNumber”,

                                                    @”California”, @”city”,

                                                    @”11″, @”rollNo”, nil];

    

    [CoreDataUtility insertData:dictionaryStudentDetail];

    }

    {

        NSMutableDictionary *dictionaryStudentDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                        @”Ales”, @”firstName”,

                                                        @”Wilson”, @”lastName”,

                                                        @”1717171717″, @”phoneNumber”,

                                                        @”USA”, @”city”,

                                                        @”12″, @”rollNo”, nil];

        

        [CoreDataUtility insertData:dictionaryStudentDetail];

    }

    {

        NSMutableDictionary *dictionaryStudentDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                        @”Steave”, @”firstName”,

                                                        @”Reonaldo”, @”lastName”,

                                                        @”123456790″, @”phoneNumber”,

                                                        @”California”, @”city”,

                                                        @”13″, @”rollNo”, nil];

        

        [CoreDataUtility insertData:dictionaryStudentDetail];

    }

    

}

– (IBAction)buttonActionFetchData:(id)sender {

    

    {

   Form *aForm = [CoreDataUtility getStudentDetailRollNo:@”11″];

    

        if (aForm != nil) {

            NSLog(@”%@”,aForm.firstName);

            NSLog(@”%@”,aForm.lastName);

            NSLog(@”%@”,aForm.phoneNumber);

            NSLog(@”%@”,aForm.city);

            NSLog(@”%@”,aForm.rollNo);

        }

    }

    

    {

        Form *aForm = [CoreDataUtility getStudentDetailRollNo:@”12″];

        

        if (aForm != nil) {

            NSLog(@”%@”,aForm.firstName);

            NSLog(@”%@”,aForm.lastName);

            NSLog(@”%@”,aForm.phoneNumber);

            NSLog(@”%@”,aForm.city);

            NSLog(@”%@”,aForm.rollNo);

        }

        

        

    }

    {

        Form *aForm = [CoreDataUtility getStudentDetailRollNo:@”13″];

        

        if (aForm != nil) {

            NSLog(@”%@”,aForm.firstName);

            NSLog(@”%@”,aForm.lastName);

            NSLog(@”%@”,aForm.phoneNumber);

            NSLog(@”%@”,aForm.city);

            NSLog(@”%@”,aForm.rollNo);

        }

    }

}

– (IBAction)buttonActionUpdataData:(id)sender {

    

    

    NSMutableDictionary *dictionaryStudentUpdateDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:

                                                          @”NewSteave”, @”firstName”,

                                                          @”NewReonaldo”, @”lastName”,

                                                          @”+91123456790″, @”phoneNumber”,

                                                          @”New York”, @”city”,

                                                          @”13″, @”rollNo”, nil];

    

    

    

    

    [CoreDataUtility updateData:dictionaryStudentUpdateDetail];

}

– (IBAction)buttonActionDeleteData:(id)sender {

    

    [CoreDataUtility deleteStudentDetailRollNo:@”12″];

}

– (IBAction)buttonActionViewAllData:(id)sender {

    

    NSArray *arrayAllData = [[NSArray alloc]initWithArray:[CoreDataUtility getAllRecords]];

    NSLog(@”%@”,arrayAllData);

    

    if (arrayAllData.count > 0)

    {

        for (int i = 0; i<[arrayAllData count]; i++)

        {

           NSLog(@”%@”,[[arrayAllData objectAtIndex:i]valueForKey:@”firstName”]);

        }

        

    }

}

– (IBAction)buttonActionDeleteAllData:(id)sender {

    

    [CoreDataUtility deleteAllRecords];

}

@end

CoreDataManager.h

#import <Foundation/Foundation.h>

#import <CoreData/CoreData.h>

@interface CoreDataManager : NSObject

@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;

@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;

@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;

+ (CoreDataManager *)sharedCoreDataManager;

– (void)saveContext;

– (NSURL *)applicationDocumentsDirectory; // nice to have to reference files for core data

@end

CoreDataManager.m

#import “CoreDataManager.h”

@implementation CoreDataManager

@synthesize managedObjectContext = _managedObjectContext;

@synthesize managedObjectModel = _managedObjectModel;

@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

+ (CoreDataManager *)sharedCoreDataManager

{

    static CoreDataManager *sharedInstance = nil;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        sharedInstance = [[CoreDataManager alloc]init];

    });

    return sharedInstance;

}

#pragma mark – Application’s Documents directory

// Returns the URL to the application’s Documents directory.

– (NSURL *)applicationDocumentsDirectory{

    // The directory the application uses to store the Core Data store file. This code uses a directory named “Apple.coreDataApple” in the application’s documents directory.

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

}

// 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

{

    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.

    if (_managedObjectModel != nil) {

        return _managedObjectModel;

    }

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@”CoreDataModel” withExtension:@”momd”];

    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return _managedObjectModel;

}

/*

// Returns the persistent store coordinator for the application.

// If the coordinator doesn’t already exist, it is created and the application’s store added to it.

– (NSPersistentStoreCoordinator *)persistentStoreCoordinator

{

// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.

if (_persistentStoreCoordinator != nil) {

return _persistentStoreCoordinator;

}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@”CoreDataModel.sqlite”];

NSError *error = nil;

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

//         Replace this implementation with code to handle the error appropriately.

//

//         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

//

//         Typical reasons for an error here include:

//         * The persistent store is not accessible;

//         * The schema for the persistent store is incompatible with current managed object model.

//         Check the error message to determine what the actual problem was.

//

//         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application’s resources directory instead of a writeable directory.

//

//         If you encounter schema incompatibility errors during development, you can reduce their frequency by:

//         * Simply deleting the existing store:

//         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

//

//         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:

//         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}

//

//         Lightweight migration will only work for a limited set of schema changes; consult “Core Data Model Versioning and Data Migration Programming Guide” for details.

NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);

abort();

}

return _persistentStoreCoordinator;

}

*/

– (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.

    if (_persistentStoreCoordinator != nil) {

        return _persistentStoreCoordinator;

    }

    

    // Create the coordinator and store

    

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@”CoreDataModel.sqlite”];

    NSError *error = nil;

    NSString *failureReason = @”There was an error creating or loading the application’s saved data.”;

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        // Report any error we got.

        NSMutableDictionary *dict = [NSMutableDictionary dictionary];

        dict[NSLocalizedDescriptionKey] = @”Failed to initialize the application’s saved data”;

        dict[NSLocalizedFailureReasonErrorKey] = failureReason;

        dict[NSUnderlyingErrorKey] = error;

        error = [NSError errorWithDomain:@”YOUR_ERROR_DOMAIN” code:9999 userInfo:dict];

        // Replace this with code to handle the error appropriately.

        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

        NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);

        abort();

    }

    

    return _persistentStoreCoordinator;

}

// 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

{

    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)

    if (_managedObjectContext != nil) {

        return _managedObjectContext;

    }

    

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (!coordinator)

    {

        return nil;

    }

    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];

    [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    

    return _managedObjectContext;

}

#pragma mark – Core Data Saving support

– (void)saveContext{

    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;

    if (managedObjectContext != nil) {

        NSError *error = nil;

        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {

            // Replace this implementation with code to handle the error appropriately.

            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);

            abort();

        }

    }

}

@end

CoreDataUtility.h

#import <Foundation/Foundation.h>

#import “CoreDataManager.h”

#import “Form.h”

@interface CoreDataUtility : NSObject

+ (void)insertData:(id)aData;

+ (Form *)getStudentDetailRollNo:(NSString *)aRollNo;

+ (void)updateData:(id)aData;

+ (void)deleteStudentDetailRollNo:(NSString *)aRollNo;

+ (NSArray *)getAllRecords;

+ (void)deleteAllRecords;

@end

CoreDataUtility.m

#import “CoreDataUtility.h”

@implementation CoreDataUtility

+ (void)insertData:(id)aData

{

    NSDictionary *dataDictionary = (NSDictionary *)aData;

    

    Form *aForm = (Form *)[NSEntityDescription insertNewObjectForEntityForName:@”Form” inManagedObjectContext:[[CoreDataManager sharedCoreDataManager]managedObjectContext]];

    

    aForm.firstName = ([dataDictionary objectForKey:@”firstName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”firstName”]);

    aForm.lastName = ([dataDictionary objectForKey:@”lastName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”lastName”]);

    aForm.phoneNumber = ([dataDictionary objectForKey:@”phoneNumber”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”phoneNumber”]);

    aForm.city = ([dataDictionary objectForKey:@”city”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”city”]);

    aForm.rollNo = ([dataDictionary objectForKey:@”rollNo”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”rollNo”]);

    

    

    NSError *error = nil;

    [[[CoreDataManager sharedCoreDataManager]managedObjectContext] save:&error];

    

}

+ (Form *)getStudentDetailRollNo:(NSString *)aRollNo

{

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@”Form” inManagedObjectContext:[[CoreDataManager sharedCoreDataManager]managedObjectContext]];

    [fetchRequest setEntity:entity];

    

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@”rollNo == %@”, aRollNo];

    [fetchRequest setPredicate:predicate];

    

    NSError *error = nil;

    

    NSArray *fetchResults = [[[CoreDataManager sharedCoreDataManager]managedObjectContext] executeFetchRequest:fetchRequest error:&error];

    

    Form *aForm = [fetchResults lastObject];

    return aForm;

    

}

+ (void)updateData:(id)aData

{

    NSDictionary *dataDictionary = (NSDictionary *)aData;

    

    NSString *rollNo = ([dataDictionary objectForKey:@”rollNo”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”rollNo”]);

    Form *aForm = [self getStudentDetailRollNo:rollNo];

    

    if (aForm != nil)

    {

        aForm.firstName = ([dataDictionary objectForKey:@”firstName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”firstName”]);

        aForm.lastName = ([dataDictionary objectForKey:@”lastName”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”lastName”]);

        aForm.phoneNumber = ([dataDictionary objectForKey:@”phoneNumber”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”phoneNumber”]);

        aForm.city = ([dataDictionary objectForKey:@”city”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”city”]);

        aForm.rollNo = ([dataDictionary objectForKey:@”rollNo”] == [NSNull null] ? @”NA”:[dataDictionary objectForKey:@”rollNo”]);

        

        NSError *error = nil;

        [[[CoreDataManager sharedCoreDataManager]managedObjectContext] save:&error];

        

    }

    else

    {

        NSLog(@”Record Not Found”);

    }

    

}

+ (void)deleteStudentDetailRollNo:(NSString *)aRollNo

{

    

    Form *aForm = [self getStudentDetailRollNo:aRollNo];

    

    if (aForm != nil)

    {

        [[[CoreDataManager sharedCoreDataManager]managedObjectContext] deleteObject:aForm];

    }

    NSError *error = nil;

    [[[CoreDataManager sharedCoreDataManager]managedObjectContext] save:&error];

}

+ (NSArray *)getAllRecords

{

    

    

    NSManagedObjectContext *context =[[CoreDataManager sharedCoreDataManager]managedObjectContext];

    

    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@”Form”];

    

    NSError *error = nil;

    NSArray *arrayresults = [context executeFetchRequest:request error:&error];

    

    for (NSManagedObject *obj in arrayresults)

    {

        NSArray *keys = [[[obj entity] attributesByName] allKeys];

        NSArray *values = [[[obj entity] attributesByName] allValues];

        

        NSLog(@”%@”,keys);

        NSLog(@”%@”,values);

        

    }

    

    return arrayresults;

}

+ (void)deleteAllRecords;

{

    

    NSPersistentStore *store = [[[[CoreDataManager sharedCoreDataManager]persistentStoreCoordinator] persistentStores] lastObject];

    NSError *error = nil;

    NSURL *storeURL = store.URL;

    [[[CoreDataManager sharedCoreDataManager]persistentStoreCoordinator] removePersistentStore:store error:&error];

    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];

    

    //Make new persistent store for future saves   (Taken From Above Answer)

    if (![[[CoreDataManager sharedCoreDataManager]persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])

    {

        // do something with the error

        NSLog(@”%@”,error);

    }

    else

    {

        NSLog(@”Data Reset”);

    }

    

}

@end

Download Sample Project From Github

Leave a comment