iOS coredata 使用

本文介绍了一个iOS应用中使用CoreData进行数据持久化的实现过程,包括AppDelegate中的CoreData配置及ViewController中增删改查的具体操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.png
  1. //
  2. //  AppDelegate.h
  3. //  IteyeBlog
  4. //
  5. //  Created by youbao on 16/9/24.
  6. //  Copyright © 2016年 youbao. All rights reserved.
  7. //

  8. #import <UIKit/UIKit.h>
  9. #import <CoreData/CoreData.h>

  10. @interface AppDelegate : UIResponder <UIApplicationDelegate>

  11. @property (strong, nonatomic) UIWindow *window;

  12. @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
  13. @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
  14. @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

  15. - (void)saveContext;
  16. - (NSURL *)applicationDocumentsDirectory;


  17. @end
复制代码
  1. //
  2. //  AppDelegate.m
  3. //  IteyeBlog
  4. //
  5. //  Created by youbao on 16/9/24.
  6. //  Copyright © 2016年 youbao. All rights reserved.
  7. //

  8. #import "AppDelegate.h"

  9. @interface AppDelegate ()

  10. @end

  11. @implementation AppDelegate


  12. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  13.     // Override point for customization after application launch.
  14.     //TODO:
  15.     
  16.     
  17.     
  18.     return YES;
  19. }

  20. - (void)applicationWillResignActive:(UIApplication *)application {
  21.     // 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.
  22.     // 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.
  23. }

  24. - (void)applicationDidEnterBackground:(UIApplication *)application {
  25.     // 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.
  26.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  27. }

  28. - (void)applicationWillEnterForeground:(UIApplication *)application {
  29.     // 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.
  30. }

  31. - (void)applicationDidBecomeActive:(UIApplication *)application {
  32.     // 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.
  33. }

  34. - (void)applicationWillTerminate:(UIApplication *)application {
  35.     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  36.     // Saves changes in the application's managed object context before the application terminates.
  37.     [self saveContext];
  38. }

  39. #pragma mark - Core Data stack

  40. @synthesize managedObjectContext = _managedObjectContext;
  41. @synthesize managedObjectModel = _managedObjectModel;
  42. @synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

  43. - (NSURL *)applicationDocumentsDirectory {
  44.     // The directory the application uses to store the Core Data store file. This code uses a directory named "com.curiousby.baoyou.cn.IteyeBlog" in the application's documents directory.
  45.     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
  46. }

  47. - (NSManagedObjectModel *)managedObjectModel {
  48.     // 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.
  49.     if (_managedObjectModel != nil) {
  50.         return _managedObjectModel;
  51.     }
  52.     NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"IteyeBlog" withExtension:@"momd"];
  53.     _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
  54.     return _managedObjectModel;
  55. }

  56. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
  57.     // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
  58.     if (_persistentStoreCoordinator != nil) {
  59.         return _persistentStoreCoordinator;
  60.     }
  61.     
  62.     // Create the coordinator and store
  63.     
  64.     _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
  65.     NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"IteyeBlog.sqlite"];
  66.     NSError *error = nil;
  67.     NSString *failureReason = @"There was an error creating or loading the application's saved data.";
  68.     if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
  69.         // Report any error we got.
  70.         NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  71.         dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
  72.         dict[NSLocalizedFailureReasonErrorKey] = failureReason;
  73.         dict[NSUnderlyingErrorKey] = error;
  74.         error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
  75.         // Replace this with code to handle the error appropriately.
  76.         // 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.
  77.         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  78.         abort();
  79.     }
  80.     
  81.     return _persistentStoreCoordinator;
  82. }


  83. - (NSManagedObjectContext *)managedObjectContext {
  84.     // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
  85.     if (_managedObjectContext != nil) {
  86.         return _managedObjectContext;
  87.     }
  88.     
  89.     NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
  90.     if (!coordinator) {
  91.         return nil;
  92.     }
  93.     _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
  94.     [_managedObjectContext setPersistentStoreCoordinator:coordinator];
  95.     return _managedObjectContext;
  96. }

  97. #pragma mark - Core Data Saving support

  98. - (void)saveContext {
  99.     NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
  100.     if (managedObjectContext != nil) {
  101.         NSError *error = nil;
  102.         if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
  103.             // Replace this implementation with code to handle the error appropriately.
  104.             // 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.
  105.             NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  106.             abort();
  107.         }
  108.     }
  109. }

  110. @end
复制代码
  1. //
  2. //  ViewController.m
  3. //  IteyeBlog
  4. //
  5. //  Created by youbao on 16/9/24.
  6. //  Copyright © 2016年 youbao. All rights reserved.
  7. //

  8. #import "ViewController.h"
  9. #import "AFHTTPSessionManager.h"
  10. #import   "UIImageView+WebCache.h"
  11. #import "AppDelegate.h"
  12. #import "OfferDBEntity.h"

  13. static NSString *const IconUrl = @"http://ods5pg0qp.bkt.clouddn.com/iteyeblog/icon.png";




  14. @interface ViewController ()
  15. @property (weak, nonatomic) IBOutlet UIButton *btn;
  16. @property (weak, nonatomic) IBOutlet UIImageView *image;


  17. @property (weak, nonatomic) IBOutlet UIButton *addLable;
  18. @property (weak, nonatomic) IBOutlet UIButton *selectLable;
  19. @property (weak, nonatomic) IBOutlet UIButton *updateLable;
  20. @property (weak, nonatomic) IBOutlet UIButton *delLable;

  21. @property(nonatomic,retain) AppDelegate* appDelegate;

  22. @end

  23. @implementation ViewController

  24. - (void)viewDidLoad {
  25.     [super viewDidLoad];
  26.     // Do any additional setup after loading the view, typically from a nib.
  27.     
  28.     self.appDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
  29. }

  30. -(IBAction) add:(id)sender{

  31.     OfferDBEntity *entity = (OfferDBEntity *)
  32.     [NSEntityDescription insertNewObjectForEntityForName:@"OfferDBEntity" inManagedObjectContext:self.appDelegate.managedObjectContext];
  33.     
  34.     entity.iconurl = IconUrl;
  35.     entity.name = @"baoyou it";
  36.     entity.desc = @"IT 工程师";
  37.     
  38.     NSError* error;
  39.     BOOL isSaveSuccess=[self.appDelegate.managedObjectContext save:&error];
  40.     if (!isSaveSuccess) {
  41.         NSLog(@"Error:%@",error);
  42.     }else{
  43.         NSLog(@"Save successful!");
  44.     }
  45.     
  46. }
  47. -(IBAction) select:(id)sender{

  48.     
  49.     NSFetchRequest* request=[[NSFetchRequest alloc] init];
  50.     NSEntityDescription* entity=[NSEntityDescription entityForName:@"OfferDBEntity" inManagedObjectContext:self.appDelegate.managedObjectContext];
  51.     [request setEntity:entity];
  52.     NSError* error=nil;
  53.     NSMutableArray* mutableFetchResult=[[self.appDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
  54.     if (mutableFetchResult==nil) {
  55.         NSLog(@"error:%@",error);
  56.     }
  57.     NSLog(@"the count of entity: %ld",[mutableFetchResult count]);
  58.     for (OfferDBEntity *entity in mutableFetchResult) {
  59.         NSLog(@"iconrl=%@,name=%@,desc=%@",entity.iconurl,entity.name ,entity.desc);
  60.     }
  61.     
  62. }
  63. -(IBAction) update:(id)sender{

  64.     NSFetchRequest* request=[[NSFetchRequest alloc] init];
  65.     NSEntityDescription* user=[NSEntityDescription entityForName:@"OfferDBEntity"  inManagedObjectContext:self.appDelegate.managedObjectContext];
  66.     [request setEntity:user];
  67.     //查询条件
  68.     NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"baoyou it"];
  69.     [request setPredicate:predicate];
  70.     NSError* error=nil;
  71.     NSMutableArray* mutableFetchResult=[[self.appDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
  72.     if (mutableFetchResult==nil) {
  73.         NSLog(@"error:%@",error);
  74.     }
  75.     NSLog(@"the count of entity: %ld",[mutableFetchResult count]);
  76.     //更新age后要进行保存,否则没更新
  77.     for (OfferDBEntity *entity in mutableFetchResult) {
  78.         [entity setDesc: @"baoyou desc"];
  79.     }
  80.     [self.appDelegate.managedObjectContext save:&error];
  81. }
  82. -(IBAction) del:(id)sender{

  83.     NSFetchRequest* request=[[NSFetchRequest alloc] init];
  84.     NSEntityDescription* user=[NSEntityDescription entityForName:@"OfferDBEntity" inManagedObjectContext:self.appDelegate.managedObjectContext];
  85.     [request setEntity:user];
  86.     NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"baoyou it"];
  87.     [request setPredicate:predicate];
  88.     NSError* error=nil;
  89.     NSMutableArray* mutableFetchResult=[[self.appDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
  90.     if (mutableFetchResult==nil) {
  91.         NSLog(@"Error:%@",error);
  92.     }http://bbs.jointforce.com/topic/25847
  93.     NSLog(@"The count of entry: %ld",[mutableFetchResult count]);
  94.     for (OfferDBEntity *entity in mutableFetchResult) {
  95.         [self.appDelegate.managedObjectContext deleteObject:entity];
  96.     }
  97.     
  98.     if ([self.appDelegate.managedObjectContext save:&error]) {
  99.         NSLog(@"Error:%@,%@",error,[error userInfo]);
  100.     }
  101. }





  102. @end
复制代码
转自解放号社区:http://bbs.jointforce.com/topic/25847
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值