coreData
整理自:http://www.jianshu.com/p/337872d95727
1.在创建项目的时候勾选使用coreData或者new file 一个DataModel
2.新建Entity,添加属性
3.添加类
4.上下文
@interface ViewController ()
{
AppDelegate *app;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
app = [UIApplication sharedApplication].delegate;
}
appDelegate中自动生成
5.增
Dog * dog = [NSEntityDescription insertNewObjectForEntityForName:@"Dog" inManagedObjectContext:app.managedObjectContext];
dog.name = [NSString stringWithFormat:@"dog%d",arc4random()%10];
dog.sex = @"公";
dog.age = [NSString stringWithFormat:@"%d",arc4random()%15];
[app.managedObjectContext save:nil];
6.删
NSEntityDescription * entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:app.managedObjectContext];
NSFetchRequest * request = [[NSFetchRequest alloc]init];
[request setEntity:entity];
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"name=%@",@"dog3"];
[request setPredicate:predicate];
NSArray * array = [app.managedObjectContext executeFetchRequest:request error:nil];
if (array.count) {
for (Dog * dog in array) {
[app.managedObjectContext deleteObject:dog];
}
[app.managedObjectContext save:nil];
NSLog(@"删除完成");
}else{
NSLog(@"没有检索到数据");
}
7.改
NSEntityDescription * entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:app.managedObjectContext];
NSFetchRequest * request = [[NSFetchRequest alloc]init];
[request setEntity:entity];
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"name!=%@",@"dog3"];
[request setPredicate:predicate];
NSArray * array = [app.managedObjectContext executeFetchRequest:request error:nil];
if (array.count) {
for (Dog * dog in array) {
dog.name = @"dog3";
}
[app.managedObjectContext save:nil];
NSLog(@"修改完成");
}else{
NSLog(@"没有检索到数据");
}
8.查
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Dog" inManagedObjectContext:app.managedObjectContext];
NSFetchRequest * request = [[NSFetchRequest alloc]init];
[request setEntity:entity];
NSArray *array =[app.managedObjectContext executeFetchRequest:request error:nil];
for (Dog * dog in array) {
NSLog(@"%@",dog.name);
}