Tuesday, July 30, 2013

Core Data Tute 2 (Add / Delete / Search)

Core Data Tute 2 (Add / Delete / Search)




Step 1
Create a project like previous tutorial .... 


Step 2

Create Entity & Attribute   like this...



Step 3

Add new Class call "ViewController" Class with ".xib" like Previous tutorial 

and Design this UI in ViewControler.xib




Step 4
change the code in "ViewController.h" class . 


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextFieldDelegate>


@property (weak, nonatomic) IBOutlet UITextField *studentNoTextField;
@property (weak, nonatomic) IBOutlet UITextField *studentNameTextField;
@property (weak, nonatomic) IBOutlet UILabel *displayLable;


- (IBAction)add:(id)sender;
- (IBAction)search:(id)sender;
- (IBAction)deleteStudent:(id)sender;

@end
------------------------------------------------------------------------------------------------------------------------
Step 5

Change the code in  "ViewController.m" class. In here You have to Import AppDelegate class

#import "ViewController.h"
#import "AppDelegate.h"

@interface ViewController ()
{
NSManagedObjectContext *context;
}

@end

@implementation ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}

// for hide the key board-----------------------------------
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
return [textField resignFirstResponder];
}


- (IBAction)add:(id)sender {

NSEntityDescription *entityDes=
[NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];

NSManagedObject *newStudent =
[[NSManagedObject alloc]initWithEntity:entityDes insertIntoManagedObjectContext:context];

[newStudent setValue:self.studentNameTextField.text forKey:@"studentName"];
[newStudent setValue:self.studentNoTextField.text forKey:@"studentNo"];

NSError *error;
[context save:&error];

self.displayLable.text=@"Student Added";

_studentNoTextField.text=@"";
_studentNameTextField.text=@"";

}


- (IBAction)deleteStudent:(id)sender{

NSEntityDescription *entityDes=
[NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];

NSFetchRequest *request=[[NSFetchRequest alloc]init];
[request setEntity:entityDes];

//we use "==" to get exact match-------------------------------------------------

NSPredicate *predicate=[NSPredicate predicateWithFormat:@"studentNo == %@",self.studentNoTextField.text];
[request setPredicate:predicate];
NSError *error;


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

if(machingData.count<=0)
{
self.displayLable.text=@"No Student Deleted";
}

else{

// int count=0;
for(NSManagedObject *obj in machingData){
[context deleteObject:obj];
//++count;
}

[context save:&error];
// self.displayLable.text=[NSString stringWithFormat:@"%d Student deleted : ",count];
self.displayLable.text=[NSString stringWithFormat:@"Student deleted"];
}

}

- (IBAction)search:(id)sender {

NSEntityDescription *entityDes=
[NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];

NSFetchRequest *request=[[NSFetchRequest alloc]init];
[request setEntity:entityDes];

//we use "==" to get exact match-------------------------------------------------

NSPredicate *predicate=[NSPredicate predicateWithFormat:@"studentNo == %@",self.studentNoTextField.text];

[request setPredicate:predicate];

NSError *error;

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

if(machingData.count<=0)
{
self.displayLable.text=@"No Person Found";
}
else{
NSString *sno;
NSString *sName;
for(NSManagedObject *obj in machingData){
sno=[obj valueForKey:@"studentNo"];
sName=[obj valueForKey:@"studentName"];
}

self.displayLable.text=[NSString stringWithFormat:@"Student No : %@ , Student Name : %@ ",sno,sName];
NSLog(@"display :studentNo %@ ,studentName %@ ",sno,sName);

}
}

- (void)viewDidLoad
{

AppDelegate *appDelegate=[[UIApplication sharedApplication]delegate];
context=[appDelegate managedObjectContext];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[[self studentNameTextField]setDelegate:self];
[[self studentNoTextField]setDelegate:self];

}

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

@end

------------------------------------------------------------------------------------------------------------------------------
Step 6

same like previous tutorial you have to set ViewController as a RootViewController in AppDelegate.
To do that....

"- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions"  method in AppDelegate.h


#import "ViewController.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

// Override point for customization after application launch.
ViewController *rootViewController=
[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
[self.window setRootViewController:rootViewController];

self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}



2 . After Click Search Button
Step 7                                                                                     

Run your App

1






















3.After Click the add Button

























Monday, July 29, 2013

Core Data in IOS (for Beginners)

Core Data in IOS (for Beginners)

Introduction
Core Data is a schema-driven object graph management and persistence framework
Fundamentally, Core Data helps you to save model objects (in the sense of the model-view-controller design pattern) to a file and get them back again.






Core Data is available on iOS 3.0 and later.


--------------------------------------------------------------------------------------
What i am going to do is...


Step 1

Create a ARC Project ....



Click the ARC also



Step 2

Click the "CoreDataTute.xdatamodeled"




Click Add Entity icon and type Student(Table name)


 Click the plus Sign to add Attribute





Step 3
click this icon to see the table



Step 4

Add new class for your Project



Step 5

Type this code in your  .h class (which you add new class in above)
#import <UIKit/UIKit.h>

@interface InsertDataViewController : UIViewController
{
 IBOutlet UITextField *nameField;

}
-(IBAction)save;
-(IBAction)Fetch;


@end

----------------------------------------------------------------

Step 6

Type this code in your  .m class (which you add new class in above)
Import the "AppDelegate.h"  .m class to your class
-----------------------------------------------------------------------------------------------------------------------

#import "InsertDataViewController.h"
#import "AppDelegate.h"

@interface InsertDataViewController ()

@end

@implementation InsertDataViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}

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


-(IBAction)save{

AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];

//Entity for table name : Team
NSEntityDescription *entity=[NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:appDelegate.managedObjectContext];

//set value for the column name
[entity setValue:nameField.text forKey:@"name"];

NSError *error;


//its returns true when values inserted in database succesfuly otherwise false
BOOL isSaved= [appDelegate.managedObjectContext save:&error]; 
NSLog(@"Successfully Saved : flags @%d",isSaved);

}


-(IBAction)Fetch{

AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];

//create Entity object for Table : Student
NSEntityDescription *entity=[NSEntityDescription entityForName:@"Student" inManagedObjectContext:appDelegate.managedObjectContext];

//create fetch request
NSFetchRequest *fetchRqst=[[NSFetchRequest alloc]init];
[fetchRqst setEntity:entity];

//Get all rows in mutable array
NSMutableArray *array=[[appDelegate.managedObjectContext executeFetchRequest:fetchRqst error:nil]mutableCopy];

//Core data return each row as managed object so we can access rows values through key value pair
for(NSManagedObject *obj in array)
{
   NSLog(@"SLIIT Student Names: %@\n",[obj valueForKey:@"name"]);
}

}

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

@end

-----------------------------------------------------------------------------------

Step 7

Design the following Ui and Connect those Method like this.....







Step 8

 go to the AppDelegate.m class and set Above viewController(in my case it is  InsertDataViewController)  as a Root View Controller
 to do that import view controller Header file to the AppDelegate.h class 
and change the code of   

"- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions"  method in AppDelegate.h

#import "InsertDataViewController.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
InsertDataViewController *rootViewController=
[[InsertDataViewController alloc] initWithNibName:@"InsertDataViewController" bundle:nil];
[self.window setRootViewController:rootViewController];

self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}

--------------------------------------------------------------------------------------------------------------

Step 9

Run Your App & insert some data and Click the fetch button ....



  • After click Save Button



this mean your successfully  added .................!

  • After Click Fetch Button