• iOS中CoreData


    #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)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.
         [self saveContext];
    }
    - (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.lanou3g.LessonCoreData" in the application's documents directory.
        
        
        
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSURL *urlPath = [NSURL fileURLWithPath:path];
        //本地的用fileURLPath
        //远程用URLWithString
        return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    }
    //managedObjectModel的getter方法
    //显示文件后缀为:xcdatamodeld,编译过后类型为:momd
    - (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.
        //lazyLoading
        if (_managedObjectModel != nil) {
            return _managedObjectModel;
        }
        NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"LessonCoreData" withExtension:@"momd"];
        //根据文件路径初始化model
        _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
        return _managedObjectModel;
    }
    
    - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
        // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
        if (_persistentStoreCoordinator != nil) {
            return _persistentStoreCoordinator;
        }
        
        // Create the coordinator and store
        //初始化coordinator
        //关联model
        _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
        //存储数据的沙盒文件地址
        NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"LessonCoreData.sqlite"];
        NSError *error = nil;
        NSString *failureReason = @"There was an error creating or loading the application's saved data.";
        //为这个协调者添加一个指定类型.指定位置的储存器文件
        //存储器一共包含四种类型:sqlite,xml,binary,inmemory
        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();
            //exit()退出程序
            //exit(0);
        }
        
        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] init];
        //协调者
        [_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
    #import "ViewController.h"
    #import "PersonEntity.h"
    #import "AppDelegate.h"
    @interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
    @property (weak, nonatomic) IBOutlet UITableView *tableView;
    //上下文
    @property (nonatomic, strong) NSManagedObjectContext *context;
    @property (nonatomic, strong)NSMutableArray *dataSourceArray;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        self.dataSourceArray = [@[] mutableCopy];
        
        //找到AppDelegate里面的上下文
        self.context = [(AppDelegate *)[UIApplication sharedApplication].delegate managedObjectContext];
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"PersonEntity"];
        NSArray *temAry = [self.context executeFetchRequest:request error:nil];
        
        [self.dataSourceArray addObjectsFromArray:temAry];
       
        
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    - (IBAction)addBtn:(id)sender {
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"PersonEntity" inManagedObjectContext:self.context];
        //创建对象
      PersonEntity *person = [[PersonEntity alloc] initWithEntity:entity insertIntoManagedObjectContext:self.context];
        
        NSArray *temArray = @[@"赵浩浩",@"王浩浩",@"李浩浩",@"张豪",@"王二麻子"];
        person.name = temArray[arc4random()%(temArray.count)];
        person.age = @(arc4random()%20 + 10);
        person.gender = @(arc4random() % 2);
        [self.dataSourceArray addObject:person];
        NSIndexPath *path = [NSIndexPath indexPathForRow:self.dataSourceArray.count - 1 inSection:0];
        [self.tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationBottom];
    }
    - (IBAction)selectBtn:(id)sender {
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"PersonEntity"];
        //谓词
        request.predicate = [NSPredicate predicateWithFormat:@"age > 18"];
        
        NSArray *temArr = [self.context executeFetchRequest:request error:nil];
        
        [self.dataSourceArray removeAllObjects];
        //往数组中添加元素
        [self.dataSourceArray addObjectsFromArray:temArr];
        //页面刷新
        [self.tableView reloadData];
    }
    - (IBAction)deledateBtn:(id)sender {
        
        if (self.tableView.isEditing) {
            [self.tableView setEditing:NO animated:YES
             ];
        }else{
            [self.tableView setEditing:YES animated:YES];
        }
        
        
    }
    //tableView 提交编辑
    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            PersonEntity *person = self.dataSourceArray[indexPath.row];
            //数组删除
            [self.dataSourceArray removeObject:person];
            //上下文删除
            [self.context deleteObject:person];
            //tableview删除对应行
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
        }
    }
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        return self.dataSourceArray.count;
    }
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        PersonEntity *p = self.dataSourceArray[indexPath.row];
        cell.textLabel.text = [p.age stringValue];
        //cell.textLabel.text = @"hello";
        return cell;
        
        
    }
    @end
    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>
    
    //NSManagedObject抽象父类,
    @interface PersonEntity : NSManagedObject
    
    @property (nonatomic, retain) NSString * name;
    @property (nonatomic, retain) NSNumber * age;
    @property (nonatomic, retain) NSNumber * gender;
    
    @end
    #import "PersonEntity.h"
    
    
    @implementation PersonEntity
    
    @dynamic name;
    @dynamic age;
    @dynamic gender;
    
    @end
  • 相关阅读:
    百度地图js lite api 支持点聚合
    看源码积累知识点
    React 16 源码瞎几把解读 【三 点 二】 react中的fiberRoot
    React 16 源码瞎几把解读 【三 点 一】 把react组件对象弄到dom中去(矛头指向fiber,fiber不解读这个过程也不知道)
    React 16 源码瞎几把解读 【二】 react组件的解析过程
    获得BAT技术专家Offer,他到底做了什么?
    Android 日常开发总结的技术经验
    理解Android虚拟机体系结构
    Android开发人员应该选择哪种语言?
    2019年Android岗位BAT等大厂面试题,希望对新的一年的你有所帮助
  • 原文地址:https://www.cnblogs.com/wohaoxue/p/4914110.html
Copyright © 2020-2023  润新知