Before start coding we have to follow some steps..
1. Create a new empty project with coredata.
. open xcode
. go to file create new project and select empty application
. Click next and do not miss to check the coredata chekbox..
next...
2. if needed we have to add CoreData.framework(by default added with core data project..)
TestAppDelegate* appdelegate = [[UIApplication sharedApplication]delegate];
NSManagedObject* context = appdelegate.managedObjectContext;
// Insert into
NSMutableArray* mutableArry = [[NSMutableArray alloc]init]
NSMutableArray* mutableArry = [[NSMutableArray alloc]init]
-(void)insertIntoCoreData
{
if([[self exstingrecord] isEqualToString:[txtName.text lowercaseString]])
{
UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Exist" message:@"Record allready exist !" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
txtName.text = [[mutableArry objectAtIndex:0]valueForKey:@"name"];
txtCity.text = [[mutableArry objectAtIndex:0]valueForKey:@"city"];
txtPass.text = [[mutableArry objectAtIndex:0]valueForKey:@"pass"];
return;
}
else
{
// Create a new object
object = [NSEntityDescription insertNewObjectForEntityForName:@"Emp" inManagedObjectContext:context];
[object setValue:self.txtName.text forKey:@"name"];
[object setValue:self.txtCity.text forKey:@"city"];
[object setValue:self.txtPass.text forKey:@"pass"];
NSError *err ;
if(![context save:&err])
{
NSLog(@"Faild");
}
else
{
UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Saved" message:@"Data saved successfully" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
txtName.text = @"";
txtCity.text = @"";
txtPass.text = @"";
}
}
[self fetchrecord];
}
// Retrieve from
-(void)fetchrecord
{
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription* entity = [NSEntityDescription entityForName:@"Emp" inManagedObjectContext:context];
[request setEntity:entity];
NSError *error = nil;
arr = [context executeFetchRequest:request error:&error];
mutableArry = [[NSMutableArray alloc]init];
[mutableArry addObjectsFromArray:arr];
[self.tblEmpDetails reloadData];
}
// Delete from
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// Delete object from database
[context deleteObject:[mutableArry objectAtIndex:indexPath.row]];
NSError *error = nil;
if (![context save:&error])
{
NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
return;
}
// Remove device from table view
[mutableArry removeObjectAtIndex:indexPath.row];
[self.tblEmpDetails deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
No comments:
Post a Comment