第一部分coredata的用法
先建立一個使用use coredata的工程,
在。xcdatamodeld文件中建立表格並為表格添加屬性
為表格添加關系,
下一步生成表格model
其中生成的model:User和Department裡面的屬性用的是@dynamic
@property有兩個對應的詞,一個是@synthesize,一個是@dynamic。如果@synthesize和@dynamic都沒寫,那麼默認的就是@syntheszie var = _var;
@synthesize的語義是如果你沒有手動實現setter方法和getter方法,那麼編譯器會自動為你加上這兩個方法。
@dynamic告訴編譯器,屬性的setter與getter方法由用戶自己實現,不自動生成。(當然對於readonly的屬性只需提供getter即可)。假如一個屬性被聲明為@dynamic var,然後你沒有提供@setter方法和@getter方法,編譯的時候沒問題,但是當程序運行到instance.var =someVar,由於缺setter方法會導致程序崩潰;或者當運行到 someVar = var時,由於缺getter方法同樣會導致崩潰。編譯時沒問題,運行時才執行相應的方法,這就是所謂的動態綁定。
然後會再appdelegate裡自動生成以下代碼:
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
//存儲在沙盒裡的具體位置
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named eims.CoreDatatest in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
//托管對象
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@CoreDatatest withExtension:@momd];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
//持久化存儲協調器
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@CoreDatatest.sqlite];
NSError *error = nil;
NSString *failureReason = @There was an error creating or loading the application's saved data.;
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @Failed to initialize the application's saved data;
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@YOUR_ERROR_DOMAIN code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@Unresolved error %@, %@, error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
//托管上下文
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@Unresolved error %@, %@, error, [error userInfo]);
abort();
}
}
}
這些代碼知道具體作用就好,如果想自己手動建立起來coredata文件,也可以自己手動寫
下面就是在viewcontroller的具體操作,
先引入appdelegate和User,Department的頭文件
在viewcontroller裡添加
@property (strong, nonatomic)AppDelegate *myAppDelegate;屬性
然後,
具體操作,
添加:
User*user = (User*)[NSEntityDescription insertNewObjectForEntityForName:@User inManagedObjectContext:self.myAppDelegate.managedObjectContext];
[user setName:_nametextfield.text];
[user setAge:[NSNumber numberWithInteger:[_agetextfield.text integerValue]]];
[user setSex:_sextextfield.text];
NSError*error;
BOOL isSaveSuccess = [myAppDelegate.managedObjectContext save:&error];//保存(容易忘)
if (!isSaveSuccess) {
NSLog(@Error:%@,error);
_attentiontextview.text = [NSString stringWithFormat:@Error:%@,error];
}else{
NSLog(@Save Successful!);
_attentiontextview.text = @Save Successful!;
}
查詢:
//數據請求(請求):命令集
NSFetchRequest*request = [[NSFetchRequest alloc]init];
//NSEntityDescription(實體描述):表
NSEntityDescription*user = [NSEntityDescription entityForName:@Department inManagedObjectContext:myAppDelegate.managedObjectContext];
[request setEntity:user];
NSError*error;
NSArray*mutablefetchResult = [myAppDelegate.managedObjectContext
executeFetchRequest:request error:&error];
if (mutablefetchResult == nil) {
NSLog(@Error: %@,mutablefetchResult);
}
NSLog(@the count of entry:%lu,[mutablefetchResult count]);
NSString*str = @;
for (Department*user in mutablefetchResult) {
// NSLog(@name:%@------age:%@-------sex:%@,user.name,user.age,user.sex);
// str = [str stringByAppendingFormat:@name:%@------age:%@-------sex:%@ ---depart:%@ ,user.name,user.age,user.sex,user.userrelationship.departmentname];
str = [str stringByAppendingFormat:@name:%@------ ,user.departmentname];
}
NSLog(@str:%@,str);
更新:
//NSFetchRequest 數據請求(請求):命令集
NSFetchRequest*request = [[NSFetchRequest alloc]init];
//NSEntityDescription(實體描述):表
NSEntityDescription*user = [NSEntityDescription entityForName:@User inManagedObjectContext:myAppDelegate.managedObjectContext];
[request setEntity:user];
//設置查詢條件 NSPredicate (謂詞):查詢語句
NSPredicate*predicate = [NSPredicate predicateWithFormat:@name == %@,@lisi];
[request setPredicate:predicate];
NSError*error;
NSArray * mutablFetchResult = [myAppDelegate.managedObjectContext executeFetchRequest:request error:&error];
if (mutablFetchResult == nil) {
NSLog(@Error:%@,error);
_attentiontextview.text = [NSString stringWithFormat:@Error:%@,error];
}
NSLog(@the count of entry:%lu,[mutablFetchResult count]);
for (User*user in mutablFetchResult) {
[user setAge:[NSNumber numberWithInteger:999]];
}
//判斷是否修改成功
BOOL isSaveSuccess = [myAppDelegate.managedObjectContext save:&error];//保存(容易忘)
if (!isSaveSuccess) {
NSLog(@Error:%@,error);
_attentiontextview.text = [NSString stringWithFormat:@Error:%@,error];
}else{
NSLog(@update Successful!);
_attentiontextview.text = @update Successful!;
}
刪除:
//數據請求(命令集)
NSFetchRequest*request = [[NSFetchRequest alloc]init];
//實體描述(表)
NSEntityDescription*user = [NSEntityDescription entityForName:@Department inManagedObjectContext:myAppDelegate.managedObjectContext];
[request setEntity:user];
//設置查詢條件
NSPredicate* predicate = [NSPredicate predicateWithFormat:@departmentname == %@,@公共事業部];
[request setPredicate:predicate];
NSError*error;
NSArray*mutableFetchResult = [myAppDelegate.managedObjectContext executeFetchRequest:request error:&error];
if (mutableFetchResult == nil) {
NSLog(@Error:%@,error);
_attentiontextview.text = [NSString stringWithFormat:@Error:%@,error];
}
NSLog(@mutableFetchResult %lu,[mutableFetchResult count]);
for (User*user in mutableFetchResult) {
[myAppDelegate.managedObjectContext deleteObject:user];
}
//判斷是否刪除成功
BOOL isDeleteSuccess = [myAppDelegate.managedObjectContext save:&error];//保存(容易忘)
if (!isDeleteSuccess) {
NSLog(@Error:%@,error);
_attentiontextview.text = [NSString stringWithFormat:@Error:%@,error];
}else{
NSLog(@delete Successful!);
_attentiontextview.text = @delete Successful!;
}
coredata並非嚴格的說是對sqlite數據庫的一個封裝,也可以用其他的數據庫,並不一定要使用sqlite3,當然了coredata的好處還是非常多的,高效,簡介,能節省至少50%的代碼量,條目清新
對於iOS開發者來說,會使用Core Data是一項必備技能。 沒有它,很多app都不會存在。當在互聯網上四處搜索Core Data學習教程,你很容易被各種各樣的術語嚇倒。事實上大部分學習教程都首先假定你已經知道了這些術語,而如果你不了解這些術語,那將會陷入困惑中。所以首先要知道關鍵的術語