-
CoreData 進行增刪改查的時候常用的類:
NSEntityDescription: 獲取實體對象
NSFetchRequest: 請求體
NSPredicate: 請求條件
NSSortDescriptor: 排序 首先
聲明一個屬性翔忽,將UIApplication單例的代理設(shè)置為它
@property(nonatomic,strong)AppDelegate *App;
self.App = [UIApplication sharedApplication].delegate;
- CoreData增:
1.獲取實體對象(下面用到)
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.App.managedObjectContext];
2.初始化的時候使用CoreData的initWithEntity進行初始化
Person *person = [[Person alloc] initWithEntity:entity insertIntoManagedObjectContext:self.App.managedObjectContext];
3.給person進行賦值
Person.name = @"呵呵"秒梳;
Person.age = 18;
4.保存數(shù)據(jù)庫
[self.App saveContext];
- CoreData刪:
1.獲取實體對象(下面用到)
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.App.managedObjectContext];
2.創(chuàng)建請求體
NSFetchRequest *requset = [[NSFetchRequest alloc] init];
3.創(chuàng)建請求條件
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age = 18"];
4.給請求體設(shè)置entity屬性羡鸥,還有predicate屬性
requset.entity = entity;
requset.predicate = predicate;
5.獲取要刪除的數(shù)據(jù)
NSArray *array = [self.managedObjectContext executeFetchRequest:requset error:nil];
6.遍歷之后榛鼎,使用deleteObject:刪除對象
for (Student *stu in array) {
[self.managedObjectContext deleteObject:stu];
}
7.保存數(shù)據(jù)
[self.App saveContext];
- CoreData:改
1.獲取實體對象
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.App.managedObjectContext];
2.創(chuàng)建請求體
NSFetchRequest *requset = [[NSFetchRequest alloc] init];
3.創(chuàng)建請求條件
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age = 18"];
4.給請求體設(shè)置entity屬性牢撼,還有predicate屬性
requset.entity = entity;
requset.predicate = predicate;
5.獲取要更改的數(shù)據(jù)
NSArray *array = [self.managedObjectContext executeFetchRequest:requset error:nil];
6.遍歷之后淮逻,修改要修改的屬性
for (Student *stu in array) {
stu.name = @"需要修改的內(nèi)容";
}
7.保存數(shù)據(jù)
[self.App saveContext];
- CoreData:查
1.獲取實體對象(下面用到)
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.App.managedObjectContext];
2.創(chuàng)建請求體
NSFetchRequest *requset = [[NSFetchRequest alloc] init];
3.創(chuàng)建請求條件
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age = 18"];
4.給請求體設(shè)置entity屬性,還有predicate屬性
requset.entity = entity;
requset.predicate = predicate;
5.獲取所查詢的內(nèi)容
NSArray *array = [self.managedObjectContext executeFetchRequest:requset error:nil];
- 總結(jié):
從以上可以看到我們使用coreData對數(shù)據(jù)庫進行操作的增刪改查就使用了幾個類皱埠,步驟都差不多肮帐,除了增加數(shù)據(jù)的時候,其他的基本都是一樣的漱逸,只要理解以上常用的類泪姨,靈活使用就可以對數(shù)據(jù)進行想要的操作了游沿。