• iOS开发学习之Core Data


    1.添加DataModel文件

    2.添加实体和属性

    3.创建NSManagedObject的子类,这里命名为Location(若没有实体属性类型是Transformable或没有额外的方法,只需要存储基本类型的话,可略过)
      注意:这里可以做一个额外的工作,在Location+CoreDataProperties.h文件中,将实体属性类型是Transformable对应的@property属性的类型从id改为需要的类型
    4.在AppDelegate.m文件添加以下代码:

    @interface AppDelegate () 

    @property (nonatomic,strong) NSManagedObjectContext *managedObjectContext;

    @property (nonatomic,strong) NSManagedObjectModel *managedObjectModel;

    @property (nonatomic,strong) NSPersistentStoreCoordinator *persistentStoreCoordinator;

    @end

    5.在AppDelegate.m文件的@implementation底部添加以下代码:

    #pragma mark - Core Data

    -(NSManagedObjectModel *)managedObjectModel

    {

        if(_managedObjectModel == nil)

        {

            NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"DataModel" ofType:@"momd"];//这里的DataModel与第1步创建的文件名对应

            NSURL *modelURL = [NSURL fileURLWithPath:modelPath];

            _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

        }

        return _managedObjectModel;

    }

    -(NSString *)documentsDirectory

    {

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentsDirectory = [paths lastObject];

        //NSLog(@"%@",documentsDirectory);

        return documentsDirectory;

    }

    -(NSString *)dataStorePath

    {

        return [[self documentsDirectory] stringByAppendingPathComponent:@"DataStore.sqlite"];

    }

    -(NSPersistentStoreCoordinator *)persistentStoreCoordinator

    {

        if(_persistentStoreCoordinator == nil)

        {

            NSURL *storeURL = [NSURL fileURLWithPath:[self dataStorePath]];

            _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];

            

            NSError *error;

            if(![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])

            {

                NSLog(@"Error adding persistent store %@,%@",error,[error userInfo]);

                abort();

            }

        }

        return _persistentStoreCoordinator;

    }

    -(NSManagedObjectContext *)managedObjectContext

    {

        if(_managedObjectContext == nil)

        {

            NSPersistentStoreCoordinator *coordinator = self.persistentStoreCoordinator;

            if(coordinator != nil)

            {

                _managedObjectContext = [[NSManagedObjectContext alloc] init];

                [_managedObjectContext setPersistentStoreCoordinator:coordinator];

            }

        }

        return _managedObjectContext;

    }

    6.在需要应用Core Data进行数据操控的视图控制器的.h头文件中添加以下代码:

    @property (nonatomic,strong) NSManagedObjectContext *managedObjectContext;

    7.在AppDelegate.m文件中分别#import以上视图控制器的.h文件,并将AppDelegate创建的managedObjectContext的指针传递给以上控制器

    如:

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

        // Override point for customization after application launch.

        UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;

        CurrentLocationViewController *currentLocationViewController = (CurrentLocationViewController *)tabBarController.viewControllers[0];

        currentLocationViewController.managedObjectContext = self.managedObjectContext;//传递指针

        

        UINavigationController *navigationController = (UINavigationController *)tabBarController.viewControllers[1];

        LocationsViewController *locationsViewController = (LocationsViewController *)navigationController.viewControllers[0];

        locationsViewController.managedObjectContext = self.managedObjectContext;//传递指针

        

        MapViewController *mapViewController = (MapViewController *)tabBarController.viewControllers[2];

        mapViewController.managedObjectContext = self.managedObjectContext;//传递指针

        

        return YES;

    }

    当以上视图控制器切换到其他需要应用Core Data操控数据的视图控制器时,可通过prepareForSegue将managedObjectContext的指针传递过去

    如:

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

    {

        if([segue.identifier isEqualToString:@"TagLocation"])

        {

            UINavigationController *navigationController = segue.destinationViewController;

            LocationDetailsViewController *controller = (LocationDetailsViewController *)navigationController.topViewController;

            controller.coordinate = _location.coordinate;

            controller.placemark = _placemark;

            controller.managedObjectContext = self.managedObjectContext;//传递指针

        }

    }

    (1)添加数据

      Location *location = [NSEntityDescription insertNewObjectForEntityForName:@"Location" inManagedObjectContext:self.managedObjectContext];

     //设置实体的属性 

        location.locationDescription = _descriptionText;

        location.category = _categoryName;

        location.latitude = @(self.coordinate.latitude);

        location.longitude = @(self.coordinate.longitude);

        location.date = _date;

        location.placemark = self.placemark;

        

        NSError *error;

        if(![self.managedObjectContext save:&error])

        {

           //添加处理错误情况的代码

            return;

        }

    (2)修改数据

      在获取数据【第(4)步】之后,对需要修改的实体的属性修改完之后,调用以下代码

        NSError *error;

        if(![self.managedObjectContext save:&error])

        {

           //添加处理错误情况的代码

            return;

        }

    (3)删除数据

        [self.managedObjectContext deleteObject:location];  //传入需要删除的数据对象(实体)

        NSError *error;

        if(![self.managedObjectContext save:&error])

        {

           //添加处理错误情况的代码

            return;

        }

    (4)获取数据:    

      // 初始化一个查询请求

      NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

      // 设置要查询的实体

      NSEntityDescription *entity = [NSEntityDescription entityForName:@"Location" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity];

      // 设置排序

      NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];

      [fetchRequest setSortDescriptors:@[sortDescriptor]];

       // 执行请求

      NSError *error;
      NSArray *foundObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

      if (foundObjects == nil) {

         //添加处理错误情况的代码    

         return;

      } 

       _locations = foundObjects;   //将获取的数据赋值给实例变量

  • 相关阅读:
    测试office2010发布cnblog文章
    【转载.SQL注入原理】SQL注入漏洞全接触入门篇
    【转载.SQL注入原理】SQL Server应用程序中的高级SQL注入
    【转载.SQL注入防范】SQL注入技术和跨站脚本攻击的检测
    获取目录对话框
    关于CFormView的滚动条和凹凸解决
    转——windows live writer向cnblog发布文章设置
    【转载.SQL注入原理】SQL注入法攻击一日通
    windows live wirter向cnblog发布日志测试
    android模拟器怎么与PC通信
  • 原文地址:https://www.cnblogs.com/guitarandcode/p/5571526.html
Copyright © 2020-2023  润新知