applink : https://drive.google.com/open?id=0BwU5Y4Xqfa42WW1KZlh0UkRmTDQ
Appdelegate.h
view.h
Appdelegate.h
#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;
@property NSMutableArray * arrayStore;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
@end
appdelegate.m
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
_arrayStore=[[NSMutableArray alloc]init];
// 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.RamCoreData" 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:@"RamCoreData" 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:@"RamCoreData.sqlite"];
NSLog(@"%@",storeURL);
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
view.h
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
@interface ViewController : UIViewController
@property AppDelegate * AD;
@property NSEntityDescription * student;
@property (strong, nonatomic) IBOutlet UITextField *nameTF;
@property (strong, nonatomic) IBOutlet UITextField *cityTF;
- (IBAction)saveAction:(id)sender;
@property (strong, nonatomic) IBOutlet UILabel *statusLabel;
@end
view.h
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
_AD=[[UIApplication sharedApplication]delegate];
_statusLabel.hidden=YES;
_student=[NSEntityDescription entityForName:@"Student" inManagedObjectContext:_AD.managedObjectContext];
// NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)saveAction:(id)sender {
NSManagedObject * managed=[[NSManagedObject alloc]initWithEntity:_student insertIntoManagedObjectContext:_AD.managedObjectContext];
[managed setValue:_nameTF.text forKey:@"name"];
[managed setValue:_cityTF.text forKey:@"city"];
NSError * err;
[managed.managedObjectContext save:&err];
if (err) {
_statusLabel.hidden=NO;
_statusLabel.text=@"Data Not Saved";
[_statusLabel setAlpha:0.0];
[UIView animateWithDuration:1.0
delay:0
options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction
animations:^(void)
{
[_statusLabel setAlpha:1.0];
}
completion:^(BOOL finished)
{
if(finished)
{
[UIView animateWithDuration:1.5
delay:4
options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction
animations:^(void)
{
[_statusLabel setAlpha:0.0];
}
completion:^(BOOL finished)
{
if(finished)
NSLog(@"Hurray. Label fadedIn & fadedOut");
}];
}
}];
}
else {
_statusLabel.hidden=NO;
_statusLabel.text=@"Data Saved";
[_statusLabel setAlpha:0.0];
[UIView animateWithDuration:1.0
delay:0
options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction
animations:^(void)
{
[_statusLabel setAlpha:1.0];
}
completion:^(BOOL finished)
{
if(finished)
{
[UIView animateWithDuration:1.5
delay:4
options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction
animations:^(void)
{
[_statusLabel setAlpha:0.0];
}
completion:^(BOOL finished)
{
if(finished)
NSLog(@"Hurray. Label fadedIn & fadedOut");
}];
}
}];
_nameTF.text=@"";
_cityTF.text=@"";
}
}
@end
tableView.h
#import <UIKit/UIKit.h>
@interface TableViewController1 : UITableViewController
- (IBAction)deleteAction:(id)sender;
@end
tableView.m
#import "TableViewController1.h"
#import "AppDelegate.h"
@interface TableViewController1 ()
{
AppDelegate * AD;
}
@end
@implementation TableViewController1
//- (NSManagedObjectContext *)managedObjectContext {
// NSManagedObjectContext *context = nil;
// id delegate = [[UIApplication sharedApplication] delegate];
// if ([delegate performSelector:@selector(managedObjectContext)]) {
// context = [delegate managedObjectContext];
// }
// return context;
//}
//- (id)initWithStyle:(UITableViewStyle)style
//{
// self = [super initWithStyle:style];
// if (self) {
// // Custom initialization
// }
// return self;
//}
- (void)viewDidLoad {
[super viewDidLoad];
AD=[[UIApplication sharedApplication]delegate];
// 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.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return AD.arrayStore.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TB" forIndexPath:indexPath];
NSManagedObject *device = [AD.arrayStore objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:@"%@", [device valueForKey:@"name"]]];
[cell.detailTextLabel setText:[NSString stringWithFormat:@"%@", [device valueForKey:@"city"]]];
// cell.textLabel.text=[AD.arrayStore objectAtIndex:indexPath.row];
// cell.detailTextLabel.text=[AD.arrayStore objectAtIndex:indexPath.row];
// [self.tableView reloadData];
// 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;
}
*/
- (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 {
NSManagedObjectContext *context = [AD managedObjectContext];
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView beginUpdates];
[context deleteObject:[AD.arrayStore objectAtIndex:indexPath.row]];
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
return;
}
// Remove device from table view
[AD.arrayStore removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView reloadData];
[tableView endUpdates];
} 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.
}
*/
//- (NSManagedObjectContext *)managedObjectContext
//{
// NSManagedObjectContext *context = nil;
// id delegate = [[UIApplication sharedApplication] delegate];
// if ([delegate performSelector:@selector(managedObjectContext)]) {
// context = [delegate managedObjectContext];
// }
// return context;
//}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [AD managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
AD.arrayStore = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSLog(@"%@",AD.arrayStore);
[self.tableView reloadData];
}
- (IBAction)deleteAction:(id)sender {
NSError * error;
NSURL * storeURL = [[AD.managedObjectContext persistentStoreCoordinator] URLForPersistentStore:[[[AD.managedObjectContext persistentStoreCoordinator] persistentStores] lastObject]];
[AD.managedObjectContext lock];
[AD.managedObjectContext reset];//to drop pending changes
//delete the store from the current managedObjectContext
if ([[AD.managedObjectContext persistentStoreCoordinator] removePersistentStore: [[[AD.managedObjectContext persistentStoreCoordinator] persistentStores] lastObject] error:&error])
{
// remove the file containing the data
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
//recreate the store like in the appDelegate method
[[[AD managedObjectContext] persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options: @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES} error:&error];
}
[AD.managedObjectContext unlock];
[AD.arrayStore removeAllObjects];
[self.tableView reloadData];
}
@end
Sign up here with your email
ConversionConversion EmoticonEmoticon