ios coredata的用法和利弊

來源:互聯網
上載者:User

標籤:

第一部分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學習教程,你很容易被各種各樣的術語嚇倒。事實上大部分學習教程都首先假定你已經知道了這些術語,而如果你不瞭解這些術語,那將會陷入困惑中。所以首先要知道關鍵的術語

  

ios coredata的用法和利弊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.