數(shù)據(jù)庫操作需要幾個基本要素:
- CoreData支持咆课,(默認(rèn)模版選擇比較關(guān)鍵,因?yàn)橛幸恍〢ppDelegate配置)
- editor自動創(chuàng)建的 db名+CoreDataClass 和 db名+CoreDataProperties
- AppDelegate 對象系羞, 通過
(AppDelegate*)[UIApplication sharedApplication].delegate;
獲得 - 數(shù)據(jù)庫鏈接的context 通過
appDelegate.persistentContainer.viewContext
獲得
然后就可以愉快的操作了:
添加對象
Dog *dog = [NSEntityDescription insertNewObjectForEntityForName:@"Dog" inManagedObjectContext:_app.persistentContainer.viewContext];
static NSInteger index = 0;
dog.name = [NSString stringWithFormat:@"tom%ld",index++];
dog.sex = @"公";
dog.age = [NSString stringWithFormat:@"%uyears",arc4random() % 15];
[_app saveContext];
注意的是數(shù)據(jù)庫不支持自動計(jì)數(shù)捣域,所以需要自己去處理,或者按照搜索排序
另外注意一點(diǎn)叔壤,添加可以對同一個內(nèi)容添加多次繁堡,所以自己做好檢測
搜索
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:_app.persistentContainer.viewContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",@"tom0"];
request.predicate = predicate;
NSArray *array = [_app.persistentContainer.viewContext executeFetchRequest :request error:nil];
for (Dog *dog in array) {
NSLog(@"dog name:%@",dog.name);
}
如果想獲得所有數(shù)值則把
request.predicate
條件清除
刪除
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:_app.persistentContainer.viewContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = entity;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",@"tom0"];
request.predicate = predicate;
NSArray *array = [_app.persistentContainer.viewContext executeFetchRequest:request error:nil];
if (array.count) {
for (Dog *dog in array) {
[_app.persistentContainer.viewContext deleteObject:dog];
}
NSLog(@"DELETE SUCCESS!!");
[_app saveContext];
} else
NSLog(@"NOT FOUND DATA");
原理就是對搜索的結(jié)果進(jìn)行操作處理
更新
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:_app.persistentContainer.viewContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = entity;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",@"tom0"];
request.predicate = predicate;
NSArray *array = [_app.persistentContainer.viewContext executeFetchRequest:request error:nil];
if (array.count) {
for (Dog *dog in array) {
dog.name = @"jerry8";
}
[_app saveContext];
NSLog(@"UPDATA SUCCESS!!");
} else
NSLog(@"NOT FOUND DATA");
都是對搜索操作的擴(kuò)展
參考:
http://www.reibang.com/p/f3a032f97c6c
多條件查詢
https://blog.csdn.net/qq_29892943/article/details/52765344