Core Data is a framework that came out after iOS5 and provides most of the flexibility to work directly with SQLite databases. It provides object-relational mapping (ORM) capabilities, that is, the ability to convert OC objects into Data to be stored in SQLite database files, You can also restore data stored in the database to OC objects, and manage your application’s data model through CoreData, greatly reducing the amount of code you need to write!

Example Demo: CoreDataLearn

1, first create a coreData model file: system or create your own

Create the required Entities in the data Model. For example, create a Student entity (the first letter must be uppercase) and add attributes such as name, age, sex, etc

3. Generate the entity class of the corresponding entity. Pay attention to the following two Settings before this, otherwise it will cause a crash

4. Generate context-associated databases

  • NSManagedObjectContext manages objects, context, persistence stores model objects, handles data interaction with applications
  • Ns-managed ObjectModel Data model, data structure to be managed
  • NSPersistentStoreCoordinator add database, set up the data store name, location, storage
  • Ns-managed object Records of managed data
  • NSFetchRequest data request
  • NSEntityDescription Entity structure of the table
①, create your own model file needs the following code to manually generate context, associated database
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"]; / / object according to the model file creation NSManagedObjectModel * model = [[NSManagedObjectModel alloc] initWithContentsOfURL: modelURL]; // create persistent storage assistant: Database / / by using model objects create assistant object NSPersistentStoreCoordinator * store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; / / the name of the database and the path nsstrings * docStr = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory NSUserDomainMask, YES) lastObject]; NSString *sqlPath = [docStr stringByAppendingPathComponent:@"coreData.sqlite"]; NSLog(@" database path = %@", sqlPath); NSURL *sqlUrl = [NSURL fileURLWithPath:sqlPath]; NSError *error = nil; Add a persistent repository and set the type and path, NSSQLiteStoreType: SQLite as the repository [store addPersistentStoreWithType: NSSQLiteStoreType configuration: nil URL: sqlUrl options: nil error: & error]; If (error) {NSLog(@" failed to add database :%@",error); } else {NSLog(@" add database successfully "); NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; / / assistant association persistence context. PersistentStoreCoordinator = store; _context = context; }Copy the code
A new class NSPersistentContainer has been created in iOS10, which is different from that generated after iOS10.

NSPersistentContainer is a container that encapsulates the CoreData Stack in your application, simplifying the creation and management of core Stack data processing to create nS-managed Object Models. NSPersistentStoreCoordinator NSManagedObjectContext. Details see the article: blog.csdn.net/u013263917/…

AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate; NSPersistentContainer * container = appDelegate.persistentContainer; NSURL * URL = [NSPersistentContainer defaultDirectoryURL]; // Return the URL path of the folder where the database is stored in the sandbox. NSManagedObjectContext *viewContext = container.viewContext; NSManagedObjectModel *managedObjectModel = container.managedObjectModel; NSPersistentStoreCoordinator *persistentStoreCoordinator = container.persistentStoreCoordinator; // Use the storage scheduler to quickly operate the database in multiple threads, very high efficiency (50 times more than the main thread operation block!!) - (void)performBackgroundTask:(void (^)(NSManagedObjectContext *))block;Copy the code

5. Add, delete, revise, check and arrange

  • Write data
// 1. Obtain a new subclass of NS-managedoBJectContext based on the Entity name and nS-ManageDoBJectContext insertNewObjectForEntityForName:@"Student" inManagedObjectContext:_context]; Student. name = [NSString stringWithFormat:@"Mr-%d", arc4Random ()%100]; student.age = arc4random()%20; student.sex = arc4random()%2 == 0 ? @beauty: @handsome guy; student.height = arc4random()%180; student.number = arc4random()%100 // 3. Save inserted data NSError *error = nil; If ([_context save:&error]) {[self alertViewWithMessage:@" Insert into database successfully "]; }else{[self alertViewWithMessage:[NSString stringWithFormat:@" failed to insert data into database, %@",error]]; }Copy the code
  • Delete the data
- (void) deleteData {/ / deletion request creation NSFetchRequest * deleRequest = [NSFetchRequest fetchRequestWithEntityName: @ "Student"]. NSPredicate *pre = predicateWithFormat:@"age < %d", 10]; deleRequest.predicate = pre; / / returns the need to delete the object array NSArray * deleArray = [_context executeFetchRequest: deleRequest error: nil]; For (Student *stu in deleArray) {[_context deleteObject:stu]; } NSError *error = nil; // Save -- remember to save if ([_context save:&error]) {[self alertViewWithMessage:@" Delete data with age < 10 "]; }else{NSLog(@" failed to delete data, %@", error); }}Copy the code
  • Update the change
/ / update, modify the - (void) the updateData {/ / create a query request NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName: @ "Student"); NSPredicate *pre = [NSPredicate predicateWithFormat:@"sex = %@", @" stud "]; request.predicate = pre; / / send the request NSArray * resArray = [_context executeFetchRequest: request error: nil]; // modify for (Student *stu in resArray) {stu.name = @" "; } // save NSError *error = nil; If ([_context save:&error]) {[self alertViewWithMessage:@" update the name of all dandy dandy dandy dandy dandy dandy dandy dandy "]; }else{NSLog(@" failed to update data, %@", error); }}Copy the code
  • Read the query
// read the query - (void)readData{/* predicate conditional instruction 1. Comparison operators >, <, ==, >=, <=,! @"number BETWEEN {1,5}" @"address IN {' Shanghai ','nanjing'}" 3 String itself :SELF Example: @"SELF == 'APPLE'" 4. String related: BEGINSWITH, ENDSWITH, CONTAINS Example: @"name BEGINSWITH[c] 'sh'" @"name ENDSWITH[d] 'ang'" // End with string 5. Wildcard: LIKE example: @ "name LIKE [CD] '* * er" / / * represents a wildcard, LIKE also accept [CD]. @ "name LIKE [CD]'????? Er *'" * Note *: Asterisk "*" : represents zero or more character question marks "?" MATCHES: NSString *regex = @"^A.+e$"; / / with A beginning, end e @ "name MATCHES % @", the regex note: [c] * case-insensitive, [d] does not distinguish between pronunciation symbols is no accent, [CD] not case-sensitive, also does not distinguish between pronunciation symbols. 7. Aggregate operations ANY, SOME: Specify ANY element in the following expressions. For example, ANY children. Age < 18. ALL: Specifies ALL elements in the following expressions. For example, ALL children. Age < 18. NONE: Specifies elements that are not in the following expressions. For example, NONE children. Age < 18. It logically equals NOT (ANY...) . IN: is equal to the SQL IN operation. The expression on the left must appear IN the collection specified on the right. For example, name IN {'Ben', 'Melissa', 'Nick'}. Tips: 1. Matching instruction keywords in predicates usually use uppercase letters. 2. If matching conditions are specified by the key path of the object, You need to use % K * / / / create a query request NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName: @ "Student"]. NSPredicate *pre = [NSPredicate predicateWithFormat:@"sex = %@", @" hottie "]; request.predicate = pre; // Request. FetchOffset = 0; // Request. FetchLimit = 6; / / send a query request NSArray * resArray = [_context executeFetchRequest: request error: nil]; [self alertViewWithMessage:@" Query all beauties "]; }Copy the code
  • The sorting
/ / sort - (void) sort {/ / create request NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName: @ "Student"); // Instantiate sort object NSSortDescriptor *ageSort = [NSSortDescriptor sortDescriptorWithKey:@"age" Ascending :YES]; NSSortDescriptor *numberSort = [NSSortDescriptor sortDescriptorWithKey:@"number"ascending:YES]; request.sortDescriptors = @[ageSort,numberSort]; NSError *error = nil; NSArray *resArray = [_context executeFetchRequest:request error:&error]; If (error == nil) {[self alertViewWithMessage:@" sort by age and number "]; }else{NSLog(@" sort failed, %@", error); }}Copy the code
CoreData debugging:

Open the Product and choose Edit Scheme. Select the Arguments, the following ArgumentsPassed On Launch add below two options, as shown in figure: (1) – com. Apple. CoreData. SQLDebug (2) 1

Example Github: CoreDataLearn

If you need to talk to me:

※ Github: github.com/wsl2ls ※ Personal blog: wsl2ls.github. IO