三个主要的类
1:NSManagedObjectModel(上下文,数据 关系)
2:NSPersistentStoreCoordinator(持久性数据协调器,和sqlite打交道的 与1建立关系,通过3执行数据交互)
3:NSManagedObjectContext(管理对象上下文)
分页查询:
分页起始索引
request.fetchoffset = 0;
分页条数
request.fetchLimit = 6;
自己写的一个代码:
1.声明:
NSManagedObjectModel *model;
NSPersistentStoreCoordinator *store;
NSManagedObjectContext *_context;
2.初始化管理上下文:
_context = [[NSManagedObjectContext alloc] init];
3.初始化上下文模型
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
4.实例化存储桥梁,需要模型
store = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];
5.添加一个持久化的数据库
NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *path = [docs[0] stringByAppendingPathComponent:@"my.db"];
NSURL *url = [NSURL fileURLWithPath:path];
NSLog(@"%@",url);
NSError *error = nil;
[store addPersistentStoreWithType: NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
if(error)
{
NSLog(@"打开数据库出错:%@",error);
}
else
{
_context.persistentStoreCoordinator = store;
NSLog(@"打开数据库成功");
}
此时数据库创建成功
6.添加纪录
People *p = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:_context];
p.name = self.name.text;
Sorce *s = [NSEntityDescription insertNewObjectForEntityForName:@"Sorce" inManagedObjectContext:_context];
p.sorce.easysorce = easytime;
保存添加
[_context save:nil];
7.查询数据库
//实例化一个查询
NSFetchRequest *request= [NSFetchRequest fetchRequestWithEntityName:@"People"];
//让congtext执行查询
NSString *textfiled = self.name.text;
request.predicate = [NSPredicate predicateWithFormat:@"name LIKE %@",textfiled];
NSArray *array = [_context executeFetchRequest:request error:nil];
for (People *p in array) {
NSString *agetextfiled = [p.age stringValue];
[self.age setText:agetextfiled];
}
if([self.age.text isEqual: @""])
{
NSString *text = @"查无此人";
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:text delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
}
8.删除一条数据
// 1. 实例化查询请求
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"People"];
// 2. 设置谓词条件
NSString *textfiled = self.name.text;
request.predicate = [NSPredicate predicateWithFormat:@"name LIKE %@",textfiled];
// 3. 由上下文查询数据
NSArray *result = [_context executeFetchRequest:request error:nil];
// 4. 输出结果
for (People *person in result) {
// 删除一条记录
[_context deleteObject:person];
break;
}
// 5. 通知_context保存数据
if ([_context save:nil]) {
NSLog(@"删除成功");
[self.age setText:@""];
[self.name setText:@""];
} else {
NSLog(@"删除失败");
}
详细的可以参考:http://blog.csdn.net/ysy441088327/article/details/8606019