Skip to content

Instantly share code, notes, and snippets.

@nishitpatel
Created February 28, 2017 12:19
Show Gist options
  • Save nishitpatel/527f06a2d07ee18627d088c2cbd0ff27 to your computer and use it in GitHub Desktop.
Save nishitpatel/527f06a2d07ee18627d088c2cbd0ff27 to your computer and use it in GitHub Desktop.
CoreData Setup
* First create Data model file with name "MyMobileStore.xcdatamodelId"
* Change Entities Name "Device"
* Add Attributes into Entities "Id, Name, Version, Company"
* Now follow above file codes to Insert, update, Delete & get data from CoreData.
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory;
@end
#import "AppDelegate.h"
#import <CoreData/CoreData.h>
@interface AppDelegate ()
@end
@implementation AppDelegate
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (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:@"MyMobileStore" withExtension:@"momd"]; //SETTARE BENE IL MODELLO
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
-(NSURL *)applicationDocumentsDirectory{
NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return 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:@"Core_Data.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;
}
- (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:NSPrivateQueueConcurrencyType];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
@end
#import <UIKit/UIKit.h>
@interface ProductListTableViewController : UITableViewController
@property (strong) NSMutableArray *devices;
@property (strong, nonatomic) IBOutlet UITableView *tableViewScripts;
@property (strong, nonatomic) IBOutlet UINib *tableCell;
@end
#import "ProductListTableViewController.h"
#import <CoreData/CoreData.h>
#import "AppDelegate.h"
#import "DeviceInfoTableViewCell.h"
#import "ViewController.h"
@interface ProductListTableViewController ()
@end
@implementation ProductListTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:self action:@selector(onRightButtonClick:)];
self.navigationItem.rightBarButtonItem = rightButton;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
NSManagedObjectContext *manageObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"Device"];
self.devices = [[manageObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
[self.tableView reloadData];
}
-(NSManagedObjectContext *)managedObjectContext{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
#pragma mark - OnNavigation bar right button click
-(void)onRightButtonClick:(id)sender{
[self performSegueWithIdentifier:@"addProductSegue" sender:self];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.devices.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"tableViewCells" owner:self options:nil];
DeviceInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
if (cell == nil){
cell = [nibArray objectAtIndex:0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
cell.deviceNameLabel.text = [NSString stringWithFormat:@"%@ - %@ %@", [device valueForKey:@"id"], [device valueForKey:@"name"], [device valueForKey:@"version"]];
cell.companyLabel.text = [device valueForKey:@"company"];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:@"updateProductSegue" sender:self];
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if([segue.identifier isEqualToString:@"updateProductSegue"]){
NSManagedObject *selectedDevice = [self.devices objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
ViewController *controller = [segue destinationViewController];
controller.device = selectedDevice;
}
}
@end
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#import "AppDelegate.h"
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *textFieldName;
@property (weak, nonatomic) IBOutlet UITextField *textFieldVersion;
@property (weak, nonatomic) IBOutlet UITextField *textFieldCompany;
@property (strong) NSManagedObject *device;
@property (weak, nonatomic) IBOutlet UIButton *deleteButton;
@end
#import "ViewController.h"
@interface ViewController (){
NSMutableArray *deviceList;
NSInteger *deviceId;
}
@end
@implementation ViewController
@synthesize device;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.deleteButton setHidden:NO];
deviceId = (NSInteger *)1;
NSLog(@"DeviceId: %lu",(long)deviceId);
[self getDeviceList];
if (self.device) {
[self.deleteButton setHidden:NO];
deviceId = (NSInteger *)[[self.device valueForKey:@"id"] integerValue];
[self.textFieldName setText:[self.device valueForKey:@"name"]];
[self.textFieldVersion setText:[self.device valueForKey:@"version"]];
[self.textFieldCompany setText:[self.device valueForKey:@"company"]];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSManagedObjectContext *)manageObjectContext{
AppDelegate *deleget = (AppDelegate *)[[UIApplication sharedApplication] delegate];
return [deleget managedObjectContext];
}
-(void)getDeviceList{
NSManagedObjectContext *manageObjectContext = [self manageObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"Device"];
deviceList = [[manageObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
if(deviceList != nil && deviceList.count > 0){
NSManagedObject *lastObj = [deviceList lastObject];
NSLog(@"RAW ID : %@",[lastObj valueForKey:@"id"]);
int rawId = [[lastObj valueForKey:@"id"] intValue];
deviceId = rawId+ 1;
}
NSLog(@"DeviceId: %lu",(long)deviceId);
}
-(BOOL)isDeviceAlreadyInsertedWithName:(NSString *)name Version:(NSString *)version andCompany:(NSString *)company{
if(deviceList != nil && deviceList.count > 0){
for (NSManagedObject *object in deviceList) {
NSString * deviceName, * deviceVersion , * company;
deviceName = [object valueForKey:@"name"];
deviceVersion = [object valueForKey:@"version"];
company = [object valueForKey:@"company"];
if([deviceName caseInsensitiveCompare:self.textFieldName.text] == NSOrderedSame && [deviceVersion caseInsensitiveCompare:self.textFieldVersion.text] == NSOrderedSame && [company caseInsensitiveCompare:self.textFieldCompany.text] == NSOrderedSame){
return true;
}
}
}
return false;
}
-(BOOL)deleteDeviceWithId:(NSNumber *)_dId{
NSManagedObjectContext *manageObjectContext = [self manageObjectContext];
NSEntityDescription *productEntity=[NSEntityDescription entityForName:@"Device" inManagedObjectContext:manageObjectContext];
NSFetchRequest *fetch=[[NSFetchRequest alloc] init];
[fetch setEntity:productEntity];
NSPredicate *p=[NSPredicate predicateWithFormat:@"id == %@", _dId];
[fetch setPredicate:p];
//... add sorts if you want them
NSError *fetchError;
NSMutableArray *fetchedProducts= [[manageObjectContext executeFetchRequest:fetch error:nil] mutableCopy];
for (NSManagedObject *product in fetchedProducts) {
[manageObjectContext deleteObject:product];
}
NSError *error = nil;
if(![manageObjectContext save:&error]){
return false;
NSLog(@"Can't Delete! %@ %@",error,[error localizedDescription]);
}
return true;
}
- (IBAction)onDeleteAction:(id)sender {
if([self deleteDeviceWithId:[NSNumber numberWithInteger:deviceId]]){
[self.navigationController popViewControllerAnimated:YES];
}else{
NSLog(@"Could't Perform this action");
return;
}
}
- (IBAction)onSaveAction:(id)sender {
NSManagedObjectContext * context = [self manageObjectContext];
if(self.device){
// Update existing device1
[self.device setValue:[NSNumber numberWithInteger:deviceId] forKey:@"id"];
[self.device setValue:self.textFieldName.text forKey:@"name"];
[self.device setValue:self.textFieldVersion.text forKey:@"version"];
[self.device setValue:self.textFieldCompany.text forKey:@"company"];
}else{
BOOL status = [self isDeviceAlreadyInsertedWithName:self.textFieldName.text Version:self.textFieldVersion.text andCompany:self.textFieldCompany.text];
if(!status){
NSManagedObject *newDevice= [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
[newDevice setValue:[NSNumber numberWithInteger:deviceId] forKey:@"id"];
[newDevice setValue:self.textFieldName.text forKey:@"name"];
[newDevice setValue:self.textFieldVersion.text forKey:@"version"];
[newDevice setValue:self.textFieldCompany.text forKey:@"company"];
}else{
NSLog(@"Record Already Inserted");
return;
}
}
NSError *error = nil;
if(![context save:&error]){
NSLog(@"Can't Save! %@ %@",error,[error localizedDescription]);
}
[self.navigationController popViewControllerAnimated:YES];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment