DEV'S

CoreData - StudentsRecord App

MyTableViewController.h
//
//  MyTableViewController.h
//  MyTableViewExample

#import <UIKit/UIKit.h>

@interface MyTableViewController : UITableViewController<UITableViewDataSource,UITableViewDelegate>{

}

@property(nonatomic,retain)NSMutableArray *studentsRecord;
@property(nonatomic,retain)NSManagedObjectContext *managedObjectContext;
@property(nonatomic,retain)NSMutableArray *personData;

@property(nonatomic,retain)NSManagedObjectContext *stdManagedObjectContext;

-(IBAction)getCallBack:(UIStoryboardSegue *)segue;
-(void)reloadStudentsRecords;

@end

MyTableViewController.m

//
//  MyTableViewController.m
//  MyTableViewExample

#import "MyTableViewController.h"
#import "AddEditViewController.h"
#import "AppDelegate.h"
#import "StudentEntity.h"

@interface MyTableViewController ()

@end

@implementation MyTableViewController

@synthesize studentsRecord;
@synthesize stdManagedObjectContext;
@synthesize personData;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    studentsRecord = [NSMutableArray array];
    
    
    [self.tableView reloadData];
    
    AppDelegate *app = [[UIApplication sharedApplication] delegate];
    
    self.stdManagedObjectContext = [app managedObjectContext];
    
    
    // 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.
    
    [self reloadStudentsRecords];
    
}

-(void)reloadStudentsRecords{
    //SELECT * FROM StudentEntity
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"StudentEntity"];
    /*
     WHERE sname = ‘Vasu’ AND ssub = ‘Math’
     NSPredicate *pre = [NSPredicate predicateWithFormat:@"sname = %@ and ssub = %@",@"Vasu",@"Math"];
     request.predicate = pre;
     */
    NSError *error;
    self.studentsRecord = [[self.stdManagedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    // self.personData = [personArray mutableCopy];
    for(int i = 0; i<[self.studentsRecord count]; i++){
        StudentEntity *stEnt = [self.studentsRecord objectAtIndex:i];
        NSLog(@"from CoreData SNAME %@",stEnt.sname);
        NSLog(@"from CoreData SSUB %@",stEnt.ssub);
    }
    
    [self.tableView reloadData];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)getCallBack:(UIStoryboardSegue *)segue{
    
    if ([segue.sourceViewController isKindOfClass:[AddEditViewController class]]){
        AddEditViewController *addEditViewCtrl = (AddEditViewController *)segue.sourceViewController;
        NSError *error = nil;
        StudentEntity *stdEntity;
        if (addEditViewCtrl.isEdit){
        //Non null value or YES, it is for Edit
            stdEntity = addEditViewCtrl.studentObject;
            
            
        }else{
        //Insert
            stdEntity = [NSEntityDescription insertNewObjectForEntityForName:@"StudentEntity" inManagedObjectContext:self.stdManagedObjectContext];

        }
        
        [stdEntity setSname:addEditViewCtrl.nameField.text];
        
        [stdEntity setSsub:addEditViewCtrl.subjectField.text];
        
        [self.stdManagedObjectContext save:&error];
        
        
        
        [self reloadStudentsRecords];
        
        
    }

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
    return [studentsRecord count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];
    
    UILabel *myLabel = [(UILabel *) cell viewWithTag:100];
    
    //NSDictionary *stdObj = [studentsRecord objectAtIndex:indexPath.row];
    StudentEntity *stdEnt = (StudentEntity *)[[self studentsRecord] objectAtIndex:indexPath.row];
    
    
    myLabel.text = stdEnt.sname;
    
    // Configure the cell…
    
    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
       // [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        StudentEntity *stdEnt = [studentsRecord objectAtIndex:indexPath.row];
        NSError *error;
        
        [self.stdManagedObjectContext deleteObject:stdEnt];
        [self.stdManagedObjectContext save:&error];
        
        [self reloadStudentsRecords];
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#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:@"editsegue"]){
        NSInteger index = [[self.tableView indexPathForSelectedRow] row];
        
        StudentEntity *stdObj = [studentsRecord objectAtIndex:index];
        AddEditViewController *addEditCtrl = (AddEditViewController *)segue.destinationViewController;
        addEditCtrl.isEdit = @"YES";
        
        addEditCtrl.studentObject = stdObj;
        
   
        
    }
}

@end

AddEditViewController.h

//
//  AddEditViewController.h
//  MyTableViewExample

#import <UIKit/UIKit.h>
#import "StudentEntity.h"

@interface AddEditViewController : UIViewController

@property(nonatomic,retain)StudentEntity *studentObject;

@property (strong, nonatomic) IBOutlet UITextField *nameField;

@property (strong, nonatomic) IBOutlet UITextField *subjectField;

@property (strong, nonatomic) IBOutlet UIButton *addEditButton;

@property(nonatomic,retain)NSString *isEdit;

-(IBAction)addEditButtonPressed:(id)sender;

@end

AddEditViewController.m

//
//  AddEditViewController.m
//  MyTableViewExample

#import "AddEditViewController.h"

@interface AddEditViewController ()

@end

@implementation AddEditViewController

@synthesize nameField,subjectField,addEditButton,studentObject,isEdit;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    nameField.text = studentObject.sname;
    subjectField.text = studentObject.ssub;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)addEditButtonPressed:(id)sender{
    
    [self performSegueWithIdentifier:@"reversesegue" 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.
}
*/

@end

LoginViewController.h

//
//  LoginViewController.h
//  MyTableViewExample

#import <UIKit/UIKit.h>

@interface LoginViewController : UIViewController
@property (strong, nonatomic) IBOutlet UITextField *passwordField;

@property (strong, nonatomic) IBOutlet UITextField *usernameField;

-(IBAction)loginButtonPressed:(id)sender;

@end

LoginViewController.m

//
//  LoginViewController.m
//  MyTableViewExample

#import "LoginViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

@synthesize usernameField,passwordField;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)loginButtonPressed:(id)sender{

    if ([[usernameField text] isEqualToString:@"admin"] && [[passwordField text] isEqualToString:@"admin"]){
        
        [self performSegueWithIdentifier:@"loginvalidationsegue" sender:self];
        
        NSLog(@"%@",@"Login Passed");
        
        
    
    }else{
        NSLog(@"%@",@"Login Failed");
    }

}

/*
#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.
}
*/

@end

StudentEntity+CoreDataProperties.h

//
//  StudentEntity+CoreDataProperties.h
//  MyTableViewExample
//

//
//  Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
//  to delete and recreate this implementation file for your updated model.
//

#import "StudentEntity.h"

NS_ASSUME_NONNULL_BEGIN

@interface StudentEntity (CoreDataProperties)

@property (nullable, nonatomic, retain) NSString *sname;
@property (nullable, nonatomic, retain) NSString *ssub;

@end

NS_ASSUME_NONNULL_END

StudentEntity+CoreDataProperties.m

//
//  StudentEntity+CoreDataProperties.m
//  MyTableViewExample
//

//  Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
//  to delete and recreate this implementation file for your updated model.
//

#import "StudentEntity+CoreDataProperties.h"

@implementation StudentEntity (CoreDataProperties)

@dynamic sname;
@dynamic ssub;

@end

StudentEntity.h

//
//  StudentEntity.h
//  MyTableViewExample
//
// 
//

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

NS_ASSUME_NONNULL_BEGIN

@interface StudentEntity : NSManagedObject

// Insert code here to declare functionality of your managed object subclass

@end

NS_ASSUME_NONNULL_END

#import "StudentEntity+CoreDataProperties.h"

StudentEntity.m

//
//  StudentEntity.m
//  MyTableViewExample
//

#import "StudentEntity.h"

@implementation StudentEntity

// Insert code here to add functionality to your managed object subclass

@end

AppDelegate.h

//
//  AppDelegate.h
//  MyTableViewExample
//

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

@end

AppDelegate.m

//
//  AppDelegate.m
//  MyTableViewExample
//

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (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:.
    // Saves changes in the application’s managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.devotek.apps.MyTableViewExample" in the application’s documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (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:@"MyTableViewExample" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (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:@"MyTableViewExample.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: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

iOS

2017-12-19 00:07:26
1) CoreData - UIDatePicker - Part2 - Final
2017-12-18 23:29:30
2) CoreData - UIDatePicker - Part1
2017-12-18 05:09:33
3) Shopping List App - Swift Part 2 - ActionSheet
2017-12-18 03:22:51
4) Shopping List App - Swift Part 1
2017-12-17 23:34:49
5) Swift - Introduction - WebService
2017-12-15 03:30:23
6) Shopping List IOS App - Part 2
2017-12-15 01:21:10
7) Shopping List IOS App - Part 1
2017-12-14 21:58:22
8) Shopping List IOS App - API Calls
2017-12-14 03:48:37
9) Delegate - Protocols - WebService
2017-12-13 04:28:23
10) NSMutableArray - NSMutableDictionary - TableViewController
2017-12-13 02:47:13
11) UITableViewController
2017-12-12 22:59:32
12) Segue Forward And Unwind
2016-02-27 03:20:22
13) GoogleMap Addon
2016-02-26 04:06:38
14) UILocalNotification With NSNotificationCenter
2016-02-25 03:51:07
15) CLLocationManager Example
2016-02-24 03:27:59
16) UIImagePickerController Using Camera And PhotoLibrary
2016-02-23 02:08:19
17) Multi Section UITableView - UIPickerView
2016-02-18 03:16:09
18) Hello World IOS App Using Swift
2016-02-17 03:10:24
19) Swift Programming Language - Playground
2016-02-15 02:06:55
20) TabBar Controller
2016-02-15 02:06:55
21) Understanding Auto Layout and Layout Constraints
2016-02-10 22:56:12
22) Shopping List App - Cloud - Part 3 - Final
2016-02-09 04:12:06
23) Shopping List App - Cloud - Part 2
2016-02-08 03:21:52
24) Shopping List App - Cloud - Part 1
2016-02-05 03:24:01
25) Protocol And Delegates With NSURLSession
2016-02-04 00:59:51
26) Webservice Using NSURLSession
2016-02-02 02:09:13
27) UIPickerView Addon - InputView And AccessoryView For UITextField
2016-02-02 02:07:12
28) Protocol And Delegates
2016-02-01 00:37:02
29) UIPickerView - Add Programmatically
2016-01-30 00:52:48
30) NSUserDefaults - UIAlertControler - Back Navigation Title Change
2016-01-29 02:01:06
31) CoreData - StudentsRecord App
2016-01-27 21:54:28
32) Manual Segue
2016-01-27 00:04:21
33) TableViewController Example
2016-01-25 02:08:16
34) NSArray And NSDictionary
2016-01-23 03:23:10
35) Reverse (Unwind) Segue
2016-01-22 00:56:28
36) ViewController - Segue - Messages
2014-12-22 05:29:28
37) WebService Example
2014-12-22 05:16:57
38) CoreData Example

© Vasudev.H / Email: tech3in@live.com