CoreData基本概述:
CoreData:把model存在面向对象的数据库(可以存在本地),常用于存取数据以及复查查询等,它通用于ios&Mac os.
property list:包含六种常用类,分别为[NSArray,NSDictionary,NSNumber,NSString,NSData],这六种类的Model可以存储在本地.
在Xcode中通过Add Entity 去添加:Attributes(属性),Relationships(关系:从属关系/一对一/一对多),Fetched properties(查询获取),然后用Entity去Create NSManagedObject subClass,即创建了对应Model.
基本介绍及Method:
一:NSManagedDocument
1.NSManagedDocument:继承于NSDocument,提供了用于管理存储的方法,用于访问CoreData.
NSManagedDocument对象初始化方法:
UIManagedDocument *aDocument = [[UIManagedDocument alloc] initWithFileURL:(NSURL *)url;
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[url path]];//右边:取指定路径文件,然后用(BOOL fileExists)判断文件是否存在.
if (fileExists) {
[aDocument openWithCompletionHandler:^(BOOL success) {
if (success) [self documentIsReady];
if (!success) NSLog(@"couldn't open document at %@",url);
}];
} else {
//在上面路径下去添加一个文件;
[self saveToURL:(NSString *)url
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success) {
if (success) [self documentIsReady];
if (!success) NSLog(@"couldn't create document at %@ ",url);
}];//回调:执行完上面后取执行Block;
- (void)documentIsReady
{
if(self.document.documentState == UIDocumentStateNormal) {
NSManagedObjectContext *context = self.document.managedObjectContext;
//start using Document;
}
}
注意:
documentStates:
UIDocumentStateClosed
UIDocumentStateSavingError
UIDocumentStateEditingDisabled
UiDocumentStateInConflict
2.NSManagedDocument会对创建的document(文件)自动保存,也可以手动,即下面的方法:
//该方法属于异步操作,在A线程上执行该方法时会自动创建一个B线程去执行,然后completionHandler回调到A线程去执行;
- (void)saveToURL:(NSString *)url
forSaveOperation:UIDocumentSaveForOverwriting
completionHandler:^(BOOL success) { };
关闭文件:
- (void)closeWithCompletionHandler:^(BOOL success) { };
3.UIManagedDocument的多个Entity之间不共享context,可以同NSNotificationController机制取获取改变通知.
二 :Context
NSManagedObjectContext:继承于UIDocument,它相当于CoreData的中心枢纽,可以用它对数据库中的对象进行增/删/该/查.
1.增:用context往Document文件插入对象:
NSManagedObjectContext *context = aDocument.managedObjectContext;
NSManagedObject *photo = [NSEntityDescription insertNewObjectForEntityForName:@"photo"
inManagedObjectContext:context];
photo.title = [flickrData objectForKey:FLICKR_PHOTO_TITLE];//设置photo的title属性;
怎么访问Document文件里的对象呢?如果Document里面存储的Entity对象是NSDictionary类型的,可以:
- (id) valueForKey:(NSString *)key;
- (void) setValue:(id)value forKey:(NSString *)key;
或:
- (id)valueForKeyPath:(NSIndexPath *)path;
- (void)setValue:(id)value forKeyPath:(NSIndexPath *)path;
2.删:删除对象
for example:
[aDocument.managedObjectContext deleteObject:photo];//如果有strong指针指向被删除的对象时,要记得把对象置为nil;
在删除前想要更新数据或做其他处理,可以利用Category添加方法:
for example:
@implementation Photo(Deletion)
- (void)prepareForDeletion
{
//do something you want;
}
for example:
NSRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photo"];
request.fetchBathSize = 20;//一次取20个对象;
request.fetchLimit = 100;//最大取对象数量限制;
request.sortDescriptors = @[sortDescriptor];//排序方式;
request.predicate= ... //查询条件(如果不指定查询条件,那边系统会无限制的获取对象).
//定义sortDescriptor:
NSSortDescription *sortDescriptor = [NSSortDescription sortDescriptorWithKey:@"title"
ascending:YES
selector:@slector(sort:)];//执行@slector(sort:)进行排序;
NSPredicate(查询条件)
for example:
NSString *serverName = @"flickr";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"thumbnailURL contains %@",serverName];//把包含serverName的对象都取出来;
可以组合查询条件:NSCompoundPredicate
for example:
NSArray *array = @[predicate1,predicate2];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:array];//and表示两个查询条件都满足;
for example:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photographer"];
NSData *yesterday = [NSData dataWithTimeIntervalSinceNow:-24*60*60];//指定时间:24小时;
request.predicate = [NSPredicate predicateWithFormat:@"any photos.uploadData > %@",yesterday];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"name" ascend ascending:YES]];