CoreData uses an object-oriented approach to manipulating data and is responsible for storing data in a database. Its underlying implementation is implemented using sqL-like techniques. CoreData provides an easy way to manage object persistence, allowing us to care about adding, deleting, changing, reading and writing objects instead of storing data.

Introduce CoreData

  1. CoreData is a data persistence framework packaged by apple and available in iOS3.0.
  2. It allows users to organize data according to an entity-attribute-value model and persist it as a binary,XML, or SQLite data file

advantages

  1. It’s an original Apple product.
  2. It saves about 30 to 70 percent of the code
  3. It supports visual modeling
  4. CoreData supports database version upgrades

Constitute a

When we create the project, check the Use CoreData option, and the system will automatically generate properties and methods that contain CoreData in the AppDelegate. And generate a file called test.xcDatamodeld.

In the AppDelegate file

The above picture is the property and method code generated automatically by the system for us. Their functions are as follows:

Three attributes:

1. ManagedObjectContext is the managed data context. It is used to manipulate the actual content, insert, query, and delete data. Can be simply interpreted as visual modeling file, we are in the visual modeling Entity automatically generated Model, it is for this object, convenient for file storage assistant management. 3. PersistentStoreCoordinator, this is a persistent storage assistant. It is the core of CoreData, which is responsible for connecting all modules, including the actual storage files.

Two methods: 1. SaveContext, its role is to we persisted in memory data. 2. ApplicationDocumentsDirectory, this method is used to obtain the real file path.

Using CoreData

This is the use of a simple example of CoreData to add, delete, change, check the use of the explanation.

We use CoreData to display data in tableView (search), add (add), delete (delete), click change (change).

UI

Create a UITableViewController in the storyboard, put it in the NavgationController, and set a right button. Associate methods with it and specify it as an Initial View Controller. Create a class file, associate it, and style the cell to Subtitle. Don’t go into detail here, if you want to understand to the [www.jianshu.com/p/872b84d98]…

Create a file

Select the.xcDatamodeld file, follow the steps above to create a Person instance, click the Editor button in the taskbar, and select the options in the red box below to create the file.

Because when we created the project, the system already generated some properties and methods for us in the AppDelegate. All we need to do is introduce the APPDelegate header file into the tableView.

code

Declare two properties, one a context object, which we use to handle all requests related to storage. The other one is the data source, the data that you use to display on the tableView.

Now that we’ve declared the properties, we need to initialize them, so we’re going to initialize them in the ViewDidLoad method, because our managedObjectContext is coming from an AppDelegate, so select the following initialization method.

AppDelegate *dele = [UIApplication sharedApplication]. Delegate; self.myContext = dele.managedObjectContext; self.allData = [NSMutableArray array]; [self getAllDataFromCoreData];Copy the code

Click the Add button to add data

// add data - (IBAction)addAction:(UIBarButtonItem *)sender {// create student object // create an entity description object NSEntityDescription *stuDis = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.myContext]; Student *stu = [[Student alloc]initWithEntity:stuDis insertIntoManagedObjectContext:self.myContext]; // Assign the attribute stu.name = @"Zhang"; stu.age = arc4random() % 73 + 1; // Update data source [self.allData addObject:stu]; / / modify interface NSIndexPath * indexPath = [NSIndexPath indexPathForRow: self. AllData. Count - 1inSection:0]; [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; // Save data to a file for persistence NSError *error = nil; [self.myContext save:&error];if(nil ! = error) { NSLog(@"Database persistence, problem");
    }
    [((AppDelegate *)[UIApplication sharedApplication].delegate) saveContext];
}
Copy the code

Query data from the database

- (void)getAllDataFromCoreData {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.myContext];
    [fetchRequest setEntity:entity]; // Sort conditions NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.myContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"How can you fill my bowl with empty hands?"); } / / add query to the data to the data source [self. AllData addObjectsFromArray: fetchedObjects]; // reload tableView [self.tableView reloadData]; }Copy the code

Click cell to change the data

(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.myContext];
    [fetchRequest setEntity:entity];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.myContext executeFetchRequest:fetchRequest error:&error];
    Student *stu = self.allData[indexPath.row];
    stu.name = @"Nicholas Cho."; stu.age = 15; // Update data source [self.allData removeAllObjects]; [self.allData addObjectsFromArray:fetchedObjects]; / / refresh the UI [self tableView reloadRowsAtIndexPaths: @ [indexPath] withRowAnimation: UITableViewRowAnimationLeft]; // Make changes local persistent [self.myContext save:nil]; }Copy the code

Set edit time right – click delete

// call - (void)tableView:(UITableView *)tableView when clicking on the delete button of tableViewCell (submit edit request) commitEditingStyle:(UITableViewCellEditingStyle)editingStyleforRowAtIndexPath:(NSIndexPath *)indexPath {Student *stu = self.alldata [indepath.row]; // Update data source [self.allData removeObject:stu]; / / update the UI [tableView deleteRowsAtIndexPaths: @ [indexPath] withRowAnimation: UITableViewRowAnimationFade]; // Delete the temporary database and persist it locally [self.myContext deleteObject:stu]; [self.myContext save:nil]; }Copy the code

Other methods, set the number of partitions, rows, and cell

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.allData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"main_cell" forIndexPath:indexPath];
    
    Student *stu = self.allData[indexPath.row];
    
    cell.textLabel.text = stu.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%d",stu.age];
    
    return cell;
}
Copy the code

Final effect