另一個常用數(shù)據(jù)庫:realm
創(chuàng)建支持CoreData的應(yīng)用
CoreData支持可視化的創(chuàng)建數(shù)據(jù)模型
每一個實體(Entity)對應(yīng)一個model類
給實體添加屬性,對應(yīng)數(shù)據(jù)庫中的字段
保存數(shù)據(jù)
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
//獲取管理上下文, 可以理解為"數(shù)據(jù)庫"
//Xcode版本以前用: NSManagedObjectContext *context =appDelegate.managedObjectContext;
NSManagedObjectContext *context = appDelegate.persistentContainer.viewContext;
//使用實體名稱創(chuàng)建一個實體(描述對象)
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
//使用實體描述創(chuàng)建管理對象腿箩,并且插入管理上下午("數(shù)據(jù)庫"),并沒有持久化
NSManagedObject *student = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
[student setValue:@"張三" forKey:@"name"];
[student setValue:@22 forKey:@"age"];
[student setValue:@"長沙" forKey:@"address"];
//持久化(保存)
if ([context save:nil]) {
NSLog(@"save success");
}
獲取數(shù)據(jù)
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = appDelegate.persistentContainer.viewContext;
//使用實體名創(chuàng)建數(shù)據(jù)請求對象
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
//執(zhí)行數(shù)據(jù)請求
NSArray *arr = [context executeFetchRequest:request error:nil];
NSLog(@"----->%@", arr);
創(chuàng)建NSManagedObject子類
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = appDelegate.persistentContainer.viewContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
Student *student = [[Student alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
//存
student.name = @"張三";
student.age = 31;
student.address = @"長沙";
if ([context save:nil]) {
NSLog(@"保存成功");
}
//取
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
NSArray *arr = [context executeFetchRequest:request error:nil];
for (Student *stu in arr) {
NSLog(@"------->%@: %hd", stu.name, stu.age);
}