Core Data浅谈系列之二 : 简单的CURD

网友投稿 256 2022-09-06

Core Data浅谈系列之二 : 简单的CURD

在 ​​上一篇​​中简单介绍了Core Data Stack,自上而下地对Core Data应用结构有个基本的认识,不过都是理论上的。这里就以上一篇的理论构建起一个可运行的Demo,执行一些简单的增删改查操作。

(图片来自Apple)

首先,我们需要建立如上图的栈结构。因此,在ViewController里添加3个属性:

[cpp] ​​view plain​​​ ​​copy​​ 1. @interface ViewController : UIViewController2. 3. @property (nonatomic, retain) NSManagedObjectModel *managedObjectModel;4. @property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;5. @property (nonatomic, retain) NSPersistentStoreCoordinator *persistentStoreCoordinator;6. 7. @end

根据前文讨论的顺序,我们首先创建managedObjectModel(在那之前需要引入CoreData Framework):

[cpp] ​​view plain​​​ ​​copy​​ 1. - (NSManagedObjectModel *)managedObjectModel2. {3. if (nil != _managedObjectModel) {4. return _managedObjectModel;5. }6. 7. _managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];8. return _managedObjectModel;9. }

接着创建NSManagedObject的生存环境 —— NSManagedObjectContext:

[cpp] ​​view plain​​​ ​​copy​​ 1. - (NSManagedObjectContext *)managedObjectContext2. {3. if (nil != _managedObjectContext) {4. return _managedObjectContext;5. }6. 7. _managedObjectContext = [[NSManagedObjectContext alloc] init];8. return _managedObjectContext;9. }

由于Demo会将数据存储到本地文件,所以还需要NSPersistentStoreCoordinator和NSManagedObjectContext配合。

下面是 ​​创建Core Data栈结构​​的完整代码:

[cpp] ​​view plain​​​ ​​copy​​ 1. #pragma mark -2. #pragma mark - Core Data Stack3. 4. - (NSManagedObjectModel *)managedObjectModel5. {6. if (nil != _managedObjectModel) {7. return _managedObjectModel;8. }9. 10. _managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];11. return _managedObjectModel;12. }13. 14. - (NSManagedObjectContext *)managedObjectContext15. {16. if (nil != _managedObjectContext) {17. return _managedObjectContext;18. }19. 20. _managedObjectContext = [[NSManagedObjectContext alloc] init];21. 22. if (self.persistentStoreCoordinator) {23. [_managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];24. }25. 26. return _managedObjectContext;27. }28. 29. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator30. {31. if (nil != _persistentStoreCoordinator) {32. return _persistentStoreCoordinator;33. }34. 35. NSString *storeType = NSSQLiteStoreType;36. "cdNBA.sqlite";37. 38. NSError *error = NULL;39. NSURL *storeURL = [NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:storeName]];40. 41. _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];42. if (![_persistentStoreCoordinator addPersistentStoreWithType:storeType configuration:nilURL:storeURL options:nil error:&error]) {43. "Error : %@\n", [error localizedDescription]);44. "Failed to create store %@ with NSSQLiteStoreType", [storeURL path]);45. }46. 47. return _persistentStoreCoordinator;48. }49. 50. #pragma mark -51. #pragma mark Application's Documents Directory52. 53. - (NSString *)applicationDocumentsDirectory54. {55. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);56. NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;57. return basePath;58. }

在搭建完基础的Core Data栈结构后,就可以写一些简单的CURD代码了:

[cpp] ​​view plain​​​ ​​copy​​ 1. #pragma mark -2. #pragma mark - CURD Operations3. 4. - (BOOL)createTeamWithName:(NSString *)teamName city:(NSString *)teamCity5. {6. if (!teamName || !teamCity) {7. return NO;8. }9. 10. "Team" inManagedObjectContext:self.managedObjectContext];11. "name"];12. "city"];13. 14. return YES;15. }16. 17. - (NSArray *)fetchTeamList18. {19. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];20. "Team" inManagedObjectContext:self.managedObjectContext]];21. 22. NSError *error = NULL;23. NSArray *array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];24. if (error) {25. "Error : %@\n", [error localizedDescription]);26. }27. 28. [fetchRequest release], fetchRequest = nil;29. 30. return array;31. }

我们可以把读写的代码放到viewDidLoad函数中:

[cpp] ​​view plain​​​ ​​copy​​ 1. - (void)viewDidLoad2. {3. [superviewDidLoad];4. // Do any additional setup after loading the view, typically from a nib.5. 6. "Heat"city:@"Miami"];7. "Lakers"city:@"LA"];8. [self saveContext];9. 10. NSArray *teamArray = [self fetchTeamList];11. if (teamArray) {12. for (NSManagedObject *teamObject in teamArray) {13. "name"];14. "city"];15. "Team info : %@, %@\n", teamName, teamCity);16. }17. }18. }

由于在context中创建的对象只是存在于内存中,所以我们还需要显式地把数据保存到sqlite文件里:

[cpp] ​​view plain​​​ ​​copy​​ 1. #pragma mark -2. #pragma mark - Save Context3. 4. - (void)saveContext5. {6. NSError *error = NULL;7. NSManagedObjectContext *moc = self.managedObjectContext;8. if (moc && [moc hasChanges] && ![moc save:&error]) {9. "Error %@, %@", error, [error localizedDescription]);10. abort();11. }12. }

最后,就是跑一下Demo,检验一下结果。

执行过一次程序后,我们可以搜索下cdNBA.sqlite文件,然后查看里面的数据:

同时,控制台也输出了数据:

[plain] ​​view plain​​​ ​​copy​​ 1. 2013-01-16 14:32:52.638 cdNBA[4717:c07] Team info : Heat, Miami2. 2013-01-16 14:32:52.639 cdNBA[4717:c07] Team info : Lakers, LA3.

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Android中GridView(九宫图)
下一篇:Core Data浅谈系列之四 : 数据模型的版本变迁
相关文章

 发表评论

暂时没有评论,来抢沙发吧~