coredata

sqlite.org

很多客户端会内置sqlite驱动包括ios

coredata是个框架不是数据库

支持xml、二进制文件、sqlite的读写

coredata框架:封装了关于sql语句的api

方便完成数据的升级更新(列入为创建好的数据库添加字段)

managedObjectcontext//被管理对象上下文 数据管理器 相当于临时数据 类似于git的临时目录

NSManagedObjectModel//被管理对象模型(数据模型器)

NSPersistentStoreCoordinator//持久化处理器(数据连接器)

获取managedObjectcontext对象

var context = (UIApplication.shareApplication().delegate as AppDelegate).managedObjectContext;

可视化建模文件中的实体可转化 模型

// 插入数据

1.需要一个描述用来确定为那个模型插入数据

NSEntityDescription *description = [NSEntityDescription entityForName:@"Clothes" inManagedObjectContext:self.myAppDelegate.managedObjectContext];

2.创建一个模型对象

Clothes *cloth = [[Clothes alloc] initWithEntity:description insertIntoManagedObjectContext:self.myAppdelegate.managedObjectContext];

cloth.name = @"NIKE";

int price = arc4random()%1000 +1;

cloth.price = [NSNumber numberWithInt:price];

3.添加到数据源

[self.arr addObject:cloth];

4.对数据管理器中的更改进行永久存储

[self.myAppDelegate saveContext];

//查询数据

1.NSFetchRequest 对象

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Clothes"];

2.设置排序

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"price" ascending:YES];

request.sortDescriptors = @[sortDescriptor];

request.fetchLimit = 10 //限制查询结果的数量

request.fetchOffset = 0 //查询的偏移量

//执行查询请求

NSError *error = nil;

NSArray *result = [self.myAppDelegate.managedObjectContext executeFetchRequest:request error:&error];

添加到数据源

[self.datasource addObjectsWithArr:result];

//删除数据

[self.myAppDelegate.managedObjectContext deleteObject:cloth];

[self.myAppDelegate saveContext];

//改

cloth.name = @"LiNING";

[self.myAppDeleagte saveContext];

 

posted @ 2017-03-23 19:41  iWillW  阅读(170)  评论(0编辑  收藏  举报