IOS CoreData development and ioscoredata Development
New Year's new weather, once my sister got married, and I decided to write a blog with a bachelor ~ End nonsense.
I do not like to use third-party Dongdong. I like the original official version. This article introduces CoreData data storage ~
Create an application
Check the Use Core Data. If not checked, add the same Data later.
Click the coredata file under look
Add an object, click Add Entity below, or use a menu to perform the same operation.
Create an object class
Then, generate the Code:
Click Create NSManagedObject Subclass..., select our User, and generate code
Before writing code, let's introduce it first. It mainly involves the following three things:
1. Managed Object Model. It can be understood as a database. It stores Entity, which is what you want to store.
2. Persistent Store Coordinate. It can be understood as a database connection. It stores data stored in specific files and other information.
3. Managed Object Context, data Context, basically all operations are through this.
Enter the write code status below:
One of the above three objects is indispensable. So, let's initialize them first.
1 // define three attributes 2 3 4 @ property (strong, nonatomic) NSManagedObjectModel * cdModel; 5 @ property (strong, nonatomic) NSManagedObjectContext * cdContext; 6 @ property (strong, nonatomic) NSPersistentStoreCoordinator * cdCoordinator;
1 - (NSManagedObjectModel *)cdModel 2 { 3 if(!_cdModel) 4 { 5 _cdModel = [NSManagedObjectModel mergedModelFromBundles:nil]; 6 } 7 8 return _cdModel; 9 }10 11 - (NSPersistentStoreCoordinator *)cdCoordinator12 {13 if(!_cdCoordinator)14 {15 //find the database16 NSString *dirPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:DBNAME];17 NSURL *dbPath = [NSURL fileURLWithPath:dirPath];18 NSError *err;19 _cdCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.cdModel];20 if(![_cdCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:dbPath options:nil error:&err])21 {22 NSLog(@"Error %@ %@",err.localizedDescription,err.localizedFailureReason);23 }24 dirPath = nil;25 dbPath = nil;26 }27 return _cdCoordinator;28 }29 30 - (NSManagedObjectContext *)cdContext31 {32 if(!_cdContext)33 {34 _cdContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];35 [_cdContext setPersistentStoreCoordinator:self.cdCoordinator];36 }37 return _cdContext;38 }
Perform the following CRUD operations
1 - (void)insertToDB:(NSString *)username password:(NSString *)password 2 { 3 User *u = (User *)[NSEntityDescription insertNewObjectForEntityForName:TBNAME inManagedObjectContext:self.cdContext]; 4 u.username = username; 5 u.password = password; 6 NSError *err; 7 if(![self.cdContext save:&err]) 8 { 9 NSLog(@"Error %@ %@",err.localizedDescription,err.localizedFailureReason);10 }11 }12 13 - (void)readFromDb14 {15 NSFetchRequest *fetch = [[NSFetchRequest alloc] init];16 NSEntityDescription *entity = [NSEntityDescription entityForName:TBNAME inManagedObjectContext:self.cdContext];17 [fetch setEntity:entity];18 NSError* err;19 NSArray *results = [self.cdContext executeFetchRequest:fetch error:&err];20 if(err)21 {22 NSLog(@"Error %@ %@",err.localizedDescription,err.localizedFailureReason);23 return;24 }25 [results enumerateObjectsUsingBlock:^(User *_Nonnull user, NSUInteger idx, BOOL * _Nonnull stop) {26 NSLog(@"----%@ %@",user.username,user.password);27 }];28 }
Okay. Let's test:
Forget it. The time is too late. If you want to go to bed, you won't be too tired. The following is the complete code.
1 // 2 // ViewController. m 3 // CoreDataTest 4 // 5 // Created by winter on 16/2/14. 6 // Copyright©2016 winter. all rights reserved. 7 // 8 9 # import "ViewController. h "10 # import <CoreData/CoreData. h> 11 # import "User. h "12 13 // define database name 14 # define DBNAME @" CoreDataTest. sqlite "15 // define entity 16 # define TBNAME @" User "17 18 19 @ interface ViewController () 20 {21 22} 23 // define three attributes 24 25 26 @ property (strong, nonatomic) NSManagedObjectModel * cdModel; 27 @ property (strong, nonato Mic) NSManagedObjectContext * cdContext; 28 @ property (strong, nonatomic) NSPersistentStoreCoordinator * cdCoordinator; 29 30 31 @ end 32 33 @ implementation ViewController 34 35 # pragma mark-implement getter Method 36 37 (NSManagedObjectModel *) cdModel 38 {39 if (! _ CdModel) 40 {41 _ cdModel = [NSManagedObjectModel mergedModelFromBundles: nil]; 42} 43 44 return _ cdModel; 45} 47-(nsistsperentstorecoordinator *) cdCoordinator 48 {49 if (! _ CdCoordinator) 50 {51 // find the database 52 NSString * dirPath = [[NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: DBNAME]; 53 NSURL * dbPath = [NSURL fileURLWithPath: dirPath]; 54 NSError * err; 55 _ cdCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: self. cdModel]; 56 if (! [_ CdCoordinator addPersistentStoreWithType: NSSQLiteStoreType configuration: nil URL: dbPath options: nil error: & err]) 57 {58 NSLog (@ "Error % @", err. localizedDescription, err. localizedFailureReason); 59} 60 dirPath = nil; 61 dbPath = nil; 62} 63 return _ cdCoordinator; 64} 65 66-(NSManagedObjectContext *) cdContext 67 {68 if (! _ CdContext) 69 {70 _ cdContext = [[NSManagedObjectContext alloc] initWithConcurrencyType: NSMainQueueConcurrencyType]; 71 [_ cdContext setPersistentStoreCoordinator: self. cdCoordinator]; 72} 73 return _ cdContext; 74} 75 76 77 # pragma mark-crud 78-(void) insertToDB :( NSString *) username password :( NSString *) password 79 {80 User * u = (User *) [NSEntityDescription insertNewObjectForEntityForName: TBNA ME inManagedObjectContext: self. cdContext]; 81 u. username = username; 82 u. password = password; 83 NSError * err; 84 if (! [Self. cdContext save: & err]) 85 {86 NSLog (@ "Error % @", err. localizedDescription, err. optional); 87} 88} 89 90-(void) readFromDb 91 {92 NSFetchRequest * fetch = [[NSFetchRequest alloc] init]; 93 NSEntityDescription * entity = [NSEntityDescription entityForName: TBNAME inManagedObjectContext: self. cdContext]; 94 [fetch setEntity: entity]; 95 NSError * err; 96 NSArray * results = [self. cdContext executeFetchRequest: fetch error: & err]; 97 if (err) 98 {99 NSLog (@ "Error % @", err. localizedDescription, err. localizedFailureReason); 100 return; 101} 102 [results enumerateObjectsUsingBlock: ^ (User * _ Nonnull user, NSUInteger idx, BOOL * _ Nonnull stop) {103 NSLog (@ "---- % @", user. username, user. password); 104}]; 105} 106 107-(void) viewDidLoad {108 [super viewDidLoad]; 109 // Do any additional setup after loading the view, typically from a nib.111 [self insertToDB: @ "wang" password: @ "password"]; 112 113} 114 115-(void) viewDidAppear :( BOOL) animated116 {117 [super viewDidAppear: animated]; 118 [self readFromDb]; 119} 120 121-(void) didReceiveMemoryWarning {122 [super didreceivemorywarning]; 123 // Dispose of any resources that can be recreated.124} 125 126 @ end