Core data 是 存储数据的一种方式,是数据持久化的最佳方式,是以面向对象的方式存储和管理数据:
其最终的存储类型可以是:Sqlite数据库,XML等;
其优点是:合理管理内存,避免使用sql的麻烦。利用CoreData需要导入CoreData框架,对象转记录,记录转对象不用SQL语句;
CoreData中的类对象
(1)NSManagedObjectContext(被管理的数据上下文)
操作实际内容(操作持久层)
作用:插入数据,查询数据,删除数据;
(2)NSManagedObjectModel(被管理的数据模型)
数据库所有表格或数据结构,包含各个实体的定义信息
作用:添加实体的属性,建立属性之间的关系
(3)NSPersistentStoreCoordinator(持久化存储助理)
相当于数据库连接器
作用:设置数据存储名字,位置,存储方式,和存储时机
(4)NSManagedObject(被管理的数据记录)
相当于数据库中的表格记录
(5)NSFetchRequest(相当于查询语句)
(6)NSEntityDescription(相当于表格结构)
以下是练习代码,为未注释
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
_context= delegate.managedObjectContext;
}
- (void)saveMsg:(UIButton *)sender
{NSLog(@"已保存");
Student *stu = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:_context];
[stu setSchoolNum:[NSNumber numberWithInt:[_fieldNum.text intValue]]];
[stu setSex:_fieldSex.text];
[stu setName:_fieldName.text];
[stu setAge:[NSNumber numberWithInt:[_fieldAge.text intValue]]];
[stu setAddress:_fieldAdd.text];
[_context save:nil];
}
-(void)selectMsg:(UIButton *)sender
{
NSFetchRequest *request= [NSFetchRequest fetchRequestWithEntityName:@"Student"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@",@"*"];
request.predicate = predicate;
NSArray *arr = [_context executeFetchRequest:request error:nil];
for (Student *obj in arr) {
NSLog(@"%@,%@,%@,%@,%@,",obj.schoolNum,obj.name,obj.age,obj.sex,obj.address);
}
}
-(void)deleateMsg:(UIButton *)sender
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
request.predicate = [NSPredicate predicateWithFormat:@"sex = 'nv'"];
NSArray *result = [_context executeFetchRequest:request error:nil];
for (Student*stu in result) {
NSLog(@"%@",stu.name);
[_context deleteObject:stu];
}if ([_context save:nil]) {
NSLog(@"已删除");
}else{
NSLog(@"未删除");
}
}
-(void)mendMsg:(UIButton *)sender
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
request.predicate = [NSPredicate predicateWithFormat:@"age<18"];
NSArray *arr = [_context executeFetchRequest:request error:nil];
for (Student *stu in arr) {
NSLog(@"%@ ,%@",stu.name,stu.age);
stu.name = @"未成年";
}
}