CoreData, UITextField, UIScrollView, NSNotification, NSObject
Click on Project_Name.xcdatamodeld
Creat Form entity and add below Attributes
ViewController.h
#import “CoreDataUtility.h”
#import “Form.h”
#import “Utility.h”
<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *textFieldCurrent;
@property (weak, nonatomic) IBOutlet UITextField *textFieldFirstName;
@property (weak, nonatomic) IBOutlet UITextField *textFieldLastName;
@property (weak, nonatomic) IBOutlet UITextField *textFieldPhoneNumber;
@property (weak, nonatomic) IBOutlet UITextField *textFieldCity;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollViewSignUp;
@property (weak, nonatomic) IBOutlet UITextField *textFieldRollNo;
ViewController.m
– (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
UITapGestureRecognizer *aGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
aGest.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:aGest];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
}
– (IBAction)buttonActionInsert:(id)sender
{
NSMutableDictionary *dictionaryStudentDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:
self.textFieldFirstName.text,@”firstName”,
self.textFieldLastName.text,@”lastName”,
self.textFieldPhoneNumber.text,@”phoneNumber”,
self.textFieldCity.text,@”city”,
self.textFieldRollNo.text,@”rollNo”, nil];
[CoreDataUtility insertData:dictionaryStudentDetail];
[self resetAllTextField];
}
– (IBAction)buttonActionEdit:(id)sender
{
Form *aForm = [CoreDataUtility getStudentDetailRollNo:self.textFieldRollNo.text];
if (aForm != nil)
{
NSLog(@”%@”,aForm.firstName);
NSLog(@”%@”,aForm.lastName);
NSLog(@”%@”,aForm.phoneNumber);
NSLog(@”%@”,aForm.city);
NSLog(@”%@”,aForm.rollNo);
self.textFieldFirstName.text = aForm.firstName;
self.textFieldLastName.text = aForm.lastName;
self.textFieldPhoneNumber.text = aForm.phoneNumber;
self.textFieldCity.text = aForm.city;
self.textFieldRollNo.text = aForm.rollNo;
}
else
{
NSLog(@”Record Not Found”);
self.textFieldFirstName.text = nil;
self.textFieldLastName.text = nil;
self.textFieldPhoneNumber.text = nil;
self.textFieldCity.text = nil;
}
}
– (IBAction)buttonActionUpdate:(id)sender
{
NSMutableDictionary *dictionaryStudentUpdateDetail = [[NSMutableDictionary alloc]initWithObjectsAndKeys:
self.textFieldFirstName.text,@”firstName”,
self.textFieldLastName.text,@”lastName”,
self.textFieldPhoneNumber.text,@”phoneNumber”,
self.textFieldCity.text,@”city”,
self.textFieldRollNo.text,@”rollNo”, nil];
[CoreDataUtility updateData:dictionaryStudentUpdateDetail];
[self resetAllTextField];
}
– (IBAction)buttonActiondelete:(id)sender
{
[CoreDataUtility deleteStudentDetailRollNo:self.textFieldRollNo.text];
[self resetAllTextField];
}
– (IBAction)buttonActionCancel:(id)sender
{
NSLog(@”buttonActionCancel”);
[self resetAllTextField];
}
– (IBAction)buttonActionGetAll:(id)sender
{
NSArray *arrayAllData = [[NSArray alloc]initWithArray:[CoreDataUtility getAllRecords]];
NSLog(@”%@”,arrayAllData);
if (arrayAllData.count > 0)
{
NSLog(@”%@”,[[arrayAllData objectAtIndex:0]valueForKey:@”firstName”]);
}
}
– (IBAction)buttonActionDeleteAll:(id)sender
{
[CoreDataUtility deleteAllRecords];
}
– (void)resetAllTextField
{
self.textFieldFirstName.text = nil;
self.textFieldLastName.text = nil;
self.textFieldPhoneNumber.text = nil;
self.textFieldCity.text = nil;
self.textFieldRollNo.text = nil;
}
#pragma mark – Gester method
– (void)tapDetected {
[self.textFieldCurrent resignFirstResponder];
}
#pragma mark – UIKeyboard show/hide notification
– (void)keyboardWillShow:(NSNotification *)iNotification {
NSLog(@”%f”, [iNotification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height);
NSDictionary *aKeyInfo = iNotification.userInfo;
NSValue *aRectValue = [aKeyInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
CGRect aRect = [aRectValue CGRectValue];
if (self.textFieldCurrent.tag == 4 || self.textFieldCurrent.tag == 5)
{
self.scrollViewSignUp.contentOffset = CGPointMake(0, (aRect.size.height) – ([UIScreen mainScreen].bounds.size.height / 6));
}
}
– (void)keyboardWillHide:(NSNotification *)iNotification {
self.scrollViewSignUp.contentOffset = CGPointMake(0, 0);
}
#pragma mark – UITextField delegate
– (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
– (void)textFieldDidBeginEditing:(UITextField *)textField {
self.textFieldCurrent = textField;
}
Utility.h
#import <Foundation/Foundation.h>
@interface Utility : NSObject
+(NSString *)descriptionForObject:(id)objct;
@end
Utility.m
#import “Utility.h”
#import <objc/message.h>
@implementation Utility
+(NSString *)descriptionForObject:(id)objct
{
unsigned int varCount;
NSMutableString *descriptionString = [[NSMutableString alloc]init];
objc_property_t *vars = class_copyPropertyList(object_getClass(objct), &varCount);
for (int i = 0; i < varCount; i++)
{
objc_property_t var = vars[i];
const char* name = property_getName (var);
NSString *keyValueString = [NSString stringWithFormat:@”n%@ = %@”,[NSString stringWithUTF8String:name],[objct valueForKey:[NSString stringWithUTF8String:name]]];
[descriptionString appendString:keyValueString];
}
free(vars);
return descriptionString;
}
@end
CoreDataUtility.h
#import <Foundation/Foundation.h>
#import “AppDelegate.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;
AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
Form *aForm = (Form *)[NSEntityDescription insertNewObjectForEntityForName:@”Form” inManagedObjectContext:aAppDelegate.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;
[aAppDelegate.managedObjectContext save:&error];
}
+ (Form *)getStudentDetailRollNo:(NSString *)aRollNo
{
AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@”Form” inManagedObjectContext:aAppDelegate.managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@”rollNo == %@”, aRollNo];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
NSArray *fetchResults = [aAppDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
Form *aForm = [fetchResults lastObject];
return aForm;
}
+ (void)updateData:(id)aData
{
NSDictionary *dataDictionary = (NSDictionary *)aData;
AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
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;
[aAppDelegate.managedObjectContext save:&error];
}
else
{
NSLog(@”Record Not Found”);
}
}
+ (void)deleteStudentDetailRollNo:(NSString *)aRollNo
{
AppDelegate *aAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
Form *aForm = [self getStudentDetailRollNo:aRollNo];
if (aForm != nil)
{
[aAppDelegate.managedObjectContext deleteObject:aForm];
}
NSError *error = nil;
[aAppDelegate.managedObjectContext save:&error];
}
+ (NSArray *)getAllRecords
{
AppDelegate *aAppdelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context =[aAppdelegate 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;
{
AppDelegate *aAppdelegate = [UIApplication sharedApplication].delegate;
NSPersistentStore *store = [aAppdelegate.persistentStoreCoordinator.persistentStores lastObject];
NSError *error = nil;
NSURL *storeURL = store.URL;
[aAppdelegate.persistentStoreCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
//Make new persistent store for future saves (Taken From Above Answer)
if (![aAppdelegate.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
// do something with the error
NSLog(@”%@”,error);
}
else
{
NSLog(@”Data Reset”);
}
}
@end