ios開發之CoreData使用

來源:互聯網
上載者:User

標籤:

1.在工程中添加build Phases的Link Binary with Libraries下添加CoreData的庫。

2.在當前工程中建立檔案選擇CoreData——>DataModel,建立一個資料模型,往該模型中添加實體Entity,entity就是對應sqlite裡面的表,一個實體對應一張表,有多個表就添加多個實體,然後往實體裡面添加屬性attributes,attributes就是sqlite表中的列。

3.在當前工程下右鍵建立CoreData ——>NSManageObject subclass,xcode會讓你選擇要產生的NSManageObjct subclass 的資料模型和實體,也就是說要產生物件模型所對應的資料庫和表,添加完成後,新產生的物件模型裡面有@dynamic 標記的對象,這是說對象的setter和getter方法由手動完成。

4.在使用CoreData的源檔案中添加頭

#import <CoreData/CoreData.h>

5.CoreData使用需要用到三個對象:

(1).NSManagedObjectContext

(2).NSManagedObjectModel

(3).NSPersistentStoreCoordinator

NSManagedObjectContext是進行資料持久化時的上下文,NSManagedObjectContext初始化時需要指定:NSPersistentStoreCoordinator

NSPersistentStoreCoordinator是資料持久化的助手,初始化時需要指定資料持久化時用到的資料存放區類型:sqlite、xml、記憶體。還指定路徑和NSManagedObjectModel

NSManagedObjectModel是物件模型

6.在源檔案中添加三個屬性:

@property ( strong , nonatomic) NSManagedObjectContext * coreDataContext;@property ( strong , nonatomic) NSManagedObjectModel *   coreDataModel;@property ( strong , nonatomic) NSPersistentStoreCoordinator  * coreDataPersistent;

 並且進行消極式載入初始化:

-(NSManagedObjectModel *) coreDataModel{    if (_coreDataModel ==nil ) {        _coreDataModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"resultsModel" withExtension:@"momd"]];    }    return _coreDataModel;}-(NSPersistentStoreCoordinator  *)coreDataPersistent{    if (_coreDataPersistent==nil) {        _coreDataPersistent = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self coreDataModel]];        NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) lastObject];        NSURL * pathURL = [NSURL  fileURLWithPath:[path stringByAppendingString:@"resultsModel.sqlite" ]];        NSError * error = nil;        NSPersistentStore * store = [ _coreDataPersistent  addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:pathURL options:nil error:&error] ;        if (!store) {            [NSException raise:@"add database error" format:@"%@" ,[error localizedDescription]];        }    }    return _coreDataPersistent ;}-(NSManagedObjectContext *) coreDataContext{    if(_coreDataContext ==nil)    {        _coreDataContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];        [_coreDataContext setPersistentStoreCoordinator:[self coreDataPersistent]];    }    return _coreDataContext;}

NSManagedObjectModel需要指定物件模型xxx.momd這個是建立的CoreData:xxx.xcdatamodeld自動在bundle下產生的。

插入資料:

 Results * insertResult = [NSEntityDescription insertNewObjectForEntityForName:@"Results" inManagedObjectContext: [self  coreDataContext]];    insertResult.in = @"123";    insertResult.re = @"ok";    insertResult.reD = @"1";    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];    insertResult.Time = [dateFormatter stringFromDate:[NSDate date]];    NSError * error = nil;    if(![[self coreDataContext] save: &error])    {        [NSException raise:@"save data to database error:" format:@"%@",[error localizedDescription]];    }

 這裡的in .re .reD .Time 分別對應實體Results裡面的屬性in .re .reD .Time 對它們賦值後調用 [context save:&error] 就直接儲存到資料庫中。

讀取資料:

 NSFetchRequest * databaseFecth = [[NSFetchRequest alloc] init];    databaseFecth.entity = [NSEntityDescription entityForName:@"Results" inManagedObjectContext:[self coreDataContext]];           NSArray * objs = [[self coreDataContext] executeFetchRequest:databaseFecth error:&error];    if(error)    {        [NSException raise:@"fetch data from database error:" format:@"%@",[error localizedDescription]];    }    for (NSManagedObject * obj in objs) {        NSLog(@"%@", obj);        }

 需要注意的是如果直接使用_context而不是[self context] 來擷取當前物件模型的上下文則會在運行時出錯:

*** Terminating app due to uncaught exception ‘NSInvalidArgumentException‘, reason: ‘+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name ‘Results‘‘

因為直接使用_context時是nil的,只有調用才不會為nil

 

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.