一、獲取程序中的appdelegate對象,以便使用其coredata相關的屬性和方法數組
AppDelegate *_app = [UIApplication sharedApplication].delegate;app
二、coredata存數據orm
//初始化實體,注意@「」裏直接放實體類名字對象
My *my = [NSEntityDescription insertNewObjectForEntityForName:@"Myimanager" inManagedObjectContext:_app.managedObjectContext];ip
my.name = @"小名";it
[_app saveContext];//保存io
NSLog(@"%@",NSHomeDirectory());request
三、查詢:只有/*一、二、3*/句時,表明查詢全部,/*五、6*/結合,設置查詢條件程序
/*1*/NSFetchRequest *request = [[NSFetchRequest alloc]init];//建立空語句方法
/*2*/NSEntityDescription *en = [NSEntityDescription entityForName:@"My" inManagedObjectContext:_app.managedObjectContext];//建立要查詢的實體
/*3*/[request setEntity:en];//建立查詢語句
/*4*/NSPredicate *p = [NSPredicate predicateWithFormat:@"name = %@ ",@"小真"];//查詢條件
/*5*/[request setPredicate:p];//將查詢條件放入查詢語句
NSArray *arr= [_app.managedObjectContext executeFetchRequest:request error:nil];//執行查詢語句,而且返回查詢結果
//便利數組
for (My *s in arr) {
NSLog(@"%@",s.name);
}
[_app saveContext];//保存
// NSArray *arr1 = [_app.managedObjectContext executeFetchRequest:request error:nil];
// for (My *s1 in arr1) {
// NSLog(@"%@",s1.name);
// }
四、刪除
NSFetchRequest *f1 =[[NSFetchRequest alloc]init];
NSEntityDescription *en1 = [NSEntityDescription entityForName:@"My" inManagedObjectContext:_app.managedObjectContext];//建立要查詢的實體
[f1 setEntity:en1];//建立查詢語句
NSPredicate *p1 = [NSPredicate predicateWithFormat:@"name = %@",@"小真"];//查詢條件
[f1 setPredicate:p1];//將查詢條件放入查詢語句
NSArray *arr1 = [_app.managedObjectContext executeFetchRequest:f1 error:nil];
for (My *s1 in arr1) {
[_app.managedObjectContext delete:s1];
}
NSFetchRequest *f2 = [[NSFetchRequest alloc]init];
[f2 setEntity:en1];
NSArray *arr3 = [_app.managedObjectContext executeFetchRequest:f2 error:nil];
NSLog(@"%@",arr3);