iOS:CoreData数据库的使用一(创建单个数据库表)
CoreData数据库框架:mac系统自带的数据库,它是苹果公司对sqlite进行封装而来的,既提供了对数据库的主要操作,也提供了具体的视图关系模型。
1 #import <UIKit/UIKit.h> 2 #import <CoreData/CoreData.h> 3 4 @interface AppDelegate : UIResponder <UIApplicationDelegate> 5 6 @property (strong, nonatomic) UIWindow *window; 7 8 @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; 9 @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel; 10 @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; 11 12 - (void)saveContext; 13 - (NSURL *)applicationDocumentsDirectory; 14 15 16 @end
AppDelegate.m(自动生成的代码,封装的是sqlite的一些函数方法)
1 #pragma mark - Core Data stack 2 3 @synthesize managedObjectContext = _managedObjectContext; 4 @synthesize managedObjectModel = _managedObjectModel; 5 @synthesize persistentStoreCoordinator = _persistentStoreCoordinator; 6 7 - (NSURL *)applicationDocumentsDirectory { 8 // The directory the application uses to store the Core Data store file. This code uses a directory named "com.bjsxt.CoreData___" in the application's documents directory. 9 return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 10 } 11 12 - (NSManagedObjectModel *)managedObjectModel { 13 // 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. 14 if (_managedObjectModel != nil) { 15 return _managedObjectModel; 16 } 17 NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreData___" withExtension:@"momd"]; 18 _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 19 return _managedObjectModel; 20 } 21 22 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 23 // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. 24 if (_persistentStoreCoordinator != nil) { 25 return _persistentStoreCoordinator; 26 } 27 28 // Create the coordinator and store 29 30 _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 31 NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreData___.sqlite"]; 32 NSError *error = nil; 33 NSString *failureReason = @"There was an error creating or loading the application's saved data."; 34 if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { 35 // Report any error we got. 36 NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 37 dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data"; 38 dict[NSLocalizedFailureReasonErrorKey] = failureReason; 39 dict[NSUnderlyingErrorKey] = error; 40 error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict]; 41 // Replace this with code to handle the error appropriately. 42 // 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. 43 NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 44 abort(); 45 } 46 47 return _persistentStoreCoordinator; 48 } 49 50 51 - (NSManagedObjectContext *)managedObjectContext { 52 // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) 53 if (_managedObjectContext != nil) { 54 return _managedObjectContext; 55 } 56 57 NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; 58 if (!coordinator) { 59 return nil; 60 } 61 _managedObjectContext = [[NSManagedObjectContext alloc] init]; 62 [_managedObjectContext setPersistentStoreCoordinator:coordinator]; 63 return _managedObjectContext; 64 } 65 66 #pragma mark - Core Data Saving support 67 68 - (void)saveContext { 69 NSManagedObjectContext *managedObjectContext = self.managedObjectContext; 70 if (managedObjectContext != nil) { 71 NSError *error = nil; 72 if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { 73 // Replace this implementation with code to handle the error appropriately. 74 // 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. 75 NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 76 abort(); 77 } 78 } 79 }
Person.h(自动生成的代码)
1 #import <Foundation/Foundation.h> 2 #import <CoreData/CoreData.h> 3 4 5 @interface Person : NSManagedObject 6 7 @property (nonatomic, retain) NSString * name; 8 @property (nonatomic, retain) NSNumber * age; 9 @property (nonatomic, retain) NSNumber * gender; 10 11 @end
Person.m(自动生成的代码)
1 #import "Person.h" 2 3 4 @implementation Person 5 6 @dynamic name; 7 @dynamic age; 8 @dynamic gender; 9 10 @end
重点来了,对数据库进行的主要操作,需要人为代码写的:
在AppDelegate.m文件中进行:
1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 2 3 //创建实体对象 4 Person *person = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Person class]) inManagedObjectContext:self.managedObjectContext]; 5 6 //设置实体对象的属性 7 person.name = @"zhangsan"; 8 person.age = @20; 9 person.gender = @'M'; 10 11 //保存数据 12 [self saveContext]; 13 14 15 //查询实体对象的数据 16 //1.创建请求对象 17 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([person class])]; 18 //2.创建排序对象 19 NSSortDescriptor *ageSort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]; 20 //3.发出请求 21 [request setSortDescriptors:@[ageSort]]; 22 //4.执行查询 23 NSError *error = nil; 24 NSArray *persons = [self.managedObjectContext executeFetchRequest:request error:&error]; 25 if(!error) 26 { 27 //遍历所有的实体对象 28 [persons enumerateObjectsUsingBlock:^(Person *person, NSUInteger idx, BOOL *stop) { 29 NSLog(@"name:%@,age:%@,gender:%c",person.name,person.age,(char)[person.gender integerValue]); 30 31 //修改对象 32 person.age = @([person.age integerValue] + 2); 33 34 35 //删除对象 36 if(idx == 2) 37 { 38 [self.managedObjectContext deleteObject:person]; 39 NSError *error = nil; 40 [self.managedObjectContext save:&error]; 41 if([person isDeleted]) 42 { 43 NSLog(@"删除成功"); 44 } 45 } 46 }]; 47 } 48 49 //保存上下文 50 [self saveContext]; 51 52 return YES; 53 }
