1.如果想建立一個帶有coreData的程式,要在項目初始化的時候勾選中
2.建立完成之後,會發現在AppDelegate裡多出了幾個屬性,和2個方法
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;- (void)saveContext;- (NSURL *)applicationDocumentsDirectory;
managedObjectContext (被管理的資料內容)操作實際內容(操作持久層)作用:插入資料,查詢資料,刪除資料
NSManagedObjectModel(被管理的資料模型)資料庫所有表格或資料結構,包含各實體的定義資訊 作用:添加實體的屬性,建立屬性之間的關係操作方法:視圖編輯器,或代碼
NSPersistentStoreCoordinator(持久化儲存助理)相當於資料庫的連接器 作用:設定資料存放區的名字,位置,儲存方式,和儲存時機
方法saveContext表示:儲存資料到持久層(資料庫)
方法applicationDocumentsDirectory表示:應用程式沙箱下的Documents目錄路徑
3.如果想建立一個實體物件的話,需要點擊.xcdatamodel,Add Entity,添加想要的欄位
4.產生對象檔案,command+n,然後選中CoreData裡的NSManagerObjectSubClass進行關聯,選中實體建立
5.添加資料
Person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext]; if (newPerson == nil){ NSLog(@"Failed to create the new person."); return NO; } newPerson.firstName = paramFirstName; newPerson.lastName = paramLastName; newPerson.age = [NSNumber numberWithUnsignedInteger:paramAge]; NSError *savingError = nil; if ([self.managedObjectContext save:&savingError]){ return YES; } else { NSLog(@"Failed to save the new person. Error = %@", savingError); }
NSEntityDescription(實體結構)相當於表格結構
6.取出資料查詢
/* Create the fetch request first */ NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; /* Here is the entity whose contents we want to read */ NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext]; /* Tell the request that we want to read the contents of the Person entity */ [fetchRequest setEntity:entity]; NSError *requestError = nil; /* And execute the fetch request on the context */ NSArray *persons = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError]; /* Make sure we get the array */ if ([persons count] > 0){ /* Go through the persons array one by one */ NSUInteger counter = 1; for (Person *thisPerson in persons){ NSLog(@"Person %lu First Name = %@", (unsigned long)counter, thisPerson.firstName); NSLog(@"Person %lu Last Name = %@", (unsigned long)counter, thisPerson.lastName); NSLog(@"Person %lu Age = %ld", (unsigned long)counter, (unsigned long)[thisPerson.age unsignedIntegerValue]); counter++; } } else { NSLog(@"Could not find any Person entities in the context."); }
7.刪除資料
/* Create the fetch request first */ NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; /* Here is the entity whose contents we want to read */ NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext]; /* Tell the request that we want to read the contents of the Person entity */ [fetchRequest setEntity:entity]; NSError *requestError = nil; /* And execute the fetch request on the context */ NSArray *persons = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError]; if ([persons count] > 0){ /* Delete the last person in the array */ Person *lastPerson = [persons lastObject]; [self.managedObjectContext deleteObject:lastPerson]; NSError *savingError = nil; if ([self.managedObjectContext save:&savingError]){ NSLog(@"Successfully deleted the last person in the array."); } else { NSLog(@"Failed to delete the last person in the array."); } } else { NSLog(@"Could not find any Person entities in the context."); }
8.排序
//排序 NSSortDescriptor *ageSort = [[NSSortDescriptor alloc]initWithKey:@"age" ascending:YES]; NSSortDescriptor *firstNameSort = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects: ageSort,firstNameSort, nil]; fetchRequest.sortDescriptors = sortDescriptors;
注意: ascending:YES 是區分排序的
--------------3.20----------------
如果之前的工程裡並沒有引入coreData,我們則可以加入CoreData.FrameWork,然後command+N
建立一個.xcdatamodel,並實現如下代碼
@property (nonatomic, retain) NSManagedObjectModel *managedObjectModel; @property (nonatomic, retain) NSManagedObjectContext *managedObjectContext; @property (nonatomic, retain) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#pragma mark - #pragma mark - Core Data Stack- (NSManagedObjectModel *)managedObjectModel{ if (nil != _managedObjectModel) { return _managedObjectModel; } _managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain]; return _managedObjectModel;}- (NSManagedObjectContext *)managedObjectContext{ if (nil != _managedObjectContext) { return _managedObjectContext; } _managedObjectContext = [[NSManagedObjectContext alloc] init]; if (self.persistentStoreCoordinator) { [_managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator]; } return _managedObjectContext;}- (NSPersistentStoreCoordinator *)persistentStoreCoordinator{ if (nil != _persistentStoreCoordinator) { return _persistentStoreCoordinator; } NSString *storeType = NSSQLiteStoreType; NSString *storeName = @"cdNBA.sqlite"; NSError *error = NULL; NSURL *storeURL = [NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:storeName]]; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel]; if (![_persistentStoreCoordinator addPersistentStoreWithType:storeType configuration:nilURL:storeURL options:nil error:&error]) { NSLog(@"Error : %@\n", [error localizedDescription]); NSAssert1(YES, @"Failed to create store %@ with NSSQLiteStoreType", [storeURL path]); } return _persistentStoreCoordinator;}#pragma mark -#pragma mark Application's Documents Directory- (NSString *)applicationDocumentsDirectory{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; return basePath;}
我們每一次儲存的時候都要調用一下managedObjectContext的save方法,因為在context中建立的對象只是存在於記憶體中,所以我們要實際把他儲存在sqlite裡面,得到applicationDocumentsDirectory方法裡的url,到前往->前往檔案夾裡可以看到你建立的sqlite