1.使用CoreData,必须添加CoreData框架
2.新建DataModel: Xcode-File-New-Core Data-Data Model, 文件名随便取,这里用Model命名
3.选中新增的DataModel文件,新建属性
3.1下面是新增好的Person\Book的属性
3.2注意Relationships,如果是"一对多"或"多对多"的关系,必须在type中选to many.例如下图,若干人都有这种书,所以Book的persons选"To Many".
4.设置好了DataModel之后,就可以生成Model了,依然是New- File -CoreData - NSManageObjectsubclass
5.生成好的Model
//
// Person.h
// Core Data的使用
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@class Book;
@interface Person : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * age;
@property (nonatomic, retain) NSString * phoneNo;
@property (nonatomic, retain) NSData * image;
@property (nonatomic, retain) NSSet *books;
@end
@interface Person (CoreDataGeneratedAccessors)
- (void)addBooksObject:(Book *)value;
- (void)removeBooksObject:(Book *)value;
- (void)addBooks:(NSSet *)values;
- (void)removeBooks:(NSSet *)values;
@end
// Person.m
// Core Data的使用
//
#import "Person.h"
#import "Book.h"
@implementation Person
@dynamic name;
@dynamic age;
@dynamic phoneNo;
@dynamic image;
@dynamic books;
@end
@property (nonatomic,strong) NSManagedObjectContext * context;
- (void)viewDidLoad
{
[super viewDidLoad];
// 打开数据库
[self openDB];
}
- (void)openDB
{
// 合并模型
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
// 初始化 数据持久化调度器
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];
// 给数据持久化调度器 新增SQLite数据库
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [doc stringByAppendingPathComponent:@"person.data"] ;
NSURL *url = [NSURL fileURLWithPath:path];
NSError *error = nil;
[psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
if (error) {
NSLog(@"打开数据库出错--%@",error.localizedDescription);
}else{
NSLog(@"打开数据库成功!");
}
// 初始化上下文,设置上下文的数据持久化调度器属性
_context = [[NSManagedObjectContext alloc]init];
_context.persistentStoreCoordinator = psc;
}
PS:打开数据库的过程:
7.数据库操作
- (void)viewDidLoad
{
[super viewDidLoad];
// 打开数据库
[self openDB];
// 新增数据
[self addperson];
// 查询数据
[self queryPersons];
// 修改数据
[self updatePersons];
// 删除数据
[self removePersons];
}
7.1新增数据
核心代码:
[NSEntityDescriptioninsertNewObjectForEntityForName:@"Person"inManagedObjectContext:_context];
[_context save:nil]
{
Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_context];
person.name = @"李四";
person.age = @20;
person.phoneNo = @"10010";
person.image = UIImageJPEGRepresentation([UIImage imageNamed:@"头像1.jpg"], 1);
Book *book1 = [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:_context];
book1.name = @"ios从入门到精通";
book1.author = @"菜鸟";
book1.price = @20;
Book *book2 = [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:_context];
book2.name = @"ios设计模式";
book2.author = @"高手";
book2.price = @10;
NSSet *books = [NSSet setWithObjects:book1, book2, nil];
person.books = books;
if ([_context save:nil]) {
NSLog(@"新增成功");
}else{
NSLog(@"新增失败");
}
}
7.2查询数据,用到了Fundation的NSPredicate(谓词),给request添加过滤条件
- (void)queryPersons
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
request.predicate = [NSPredicate predicateWithFormat:@"name LIKE '*三' "];
NSArray *array = [_context executeFetchRequest:request error:nil];
for (Person *p in array) {
NSLog(@"姓名:%@ ,年龄:%@ ,电话:%@",p.name,p.age,p.phoneNo);
}
}
- (void)updatePersons
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
request.predicate = [NSPredicate predicateWithFormat:@"phoneNo = '10010' "];
NSArray *array = [_context executeFetchRequest:request error:nil];
for (Person *p in array) {
p.name = @"加强版李四11";
}
if ([_context save:nil]) {
NSLog(@"更新成功");
}else{
NSLog(@"更新失败");
}
}
7.4删除数据
- (void)removePersons
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
request.predicate = [NSPredicate predicateWithFormat:@"name LIKE '*李四11'"];
NSArray *array = [_context executeFetchRequest:request error:nil];
for (Person *p in array) {
[_context deleteObject:p];
}
if ([_context save:nil]) {
NSLog(@"删除成功");
}else{
NSLog(@"删除失败");
}
}
查询\更新\删除的核心代码:
[NSFetchRequestfetchRequestWithEntityName:@"Person"]; // 请求
[_contextexecuteFetchRequest:requesterror:nil]; // 上下文执行请求
除了查询, 更新\删除都用到了 [ _context save : nil ],因为更新\删除涉及到对数据库的修改