CoreData实际应用

来源:互联网 发布:网络收短信 编辑:程序博客网 时间:2024/06/07 16:46

最近在看CoreData的知识,看了很多人的博客,有很多都是在讲理论,我这里想更多的去学习怎么去使用。


CoreData的理论大概就是:在应用程序和数据库之间,加载了一层缓冲区,用来提供用户简介的存储数据和获取数据,这样就避免了与底层的操作,从而也不用开发者会太多的SQL语句。


Demo的UI如下,no是NO.,用来演示排序,Add是往数据库Save数据,Query是根绝排序获取数据并显示出来。




AppDelegate.h和AppDelegate.m的变化(这个可以直接粘贴复制,基本上用CoreData不会变动):

@interface pelAppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;//数据模型对象@property(strong,nonatomic) NSManagedObjectModel *managedObjectModel;//上下文对象@property(strong,nonatomic) NSManagedObjectContext *managedObjectContext;//持久性存储区@property(strong,nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;//初始化Core Data使用的数据库-(NSPersistentStoreCoordinator *)persistentStoreCoordinator;//managedObjectModel的初始化赋值函数-(NSManagedObjectModel *)managedObjectModel;//managedObjectContext的初始化赋值函数-(NSManagedObjectContext *)managedObjectContext;@end


//CoreData-(NSManagedObjectModel *)managedObjectModel{    if (managedObjectModel != nil) {        return managedObjectModel;    }    managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];    return managedObjectModel;}-(NSPersistentStoreCoordinator *)persistentStoreCoordinator{    if (persistentStoreCoordinator != nil) {        return persistentStoreCoordinator;    }    //得到数据库的路径    NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];    //CoreData是建立在SQLite之上的,数据库名称需与Xcdatamodel文件同名    NSURL *storeUrl = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"CDJournal.sqlite"]];    NSError *error = nil;    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:[self managedObjectModel]];    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {        NSLog(@"Error: %@,%@",error,[error userInfo]);    }    return persistentStoreCoordinator;}-(NSManagedObjectContext *)managedObjectContext{    if (managedObjectContext != nil) {        return managedObjectContext;    }    NSPersistentStoreCoordinator *coordinator =[self persistentStoreCoordinator];    if (coordinator != nil) {        managedObjectContext = [[NSManagedObjectContext alloc]init];        [managedObjectContext setPersistentStoreCoordinator:coordinator];    }    return managedObjectContext;}


viewController.h: 其它都好理解,只有两个会不同,第一个:

pelAppDelegate *myDelegate   :   这个是用来存放获取AppDelegate的对象。
NSMutableArray * entries  :  这个用来存放获取数据库后的数组数据。

@interface pelViewController : UIViewController@property (strong, nonatomic) IBOutlet UITextField *titleText;@property (strong, nonatomic) IBOutlet UITextField *contentText;@property (strong, nonatomic) IBOutlet UITextField *noText;@property (strong,nonatomic) pelAppDelegate *myDelegate;@property (strong,nonatomic) NSMutableArray * entries;- (IBAction)Add:(id)sender;- (IBAction)query:(id)sender;@end

最关键的是ViewController.m文件,代码如下:
@interface pelViewController ()@end@implementation pelViewController- (void)viewDidLoad{    [super viewDidLoad];self.myDelegate = (pelAppDelegate *)[[UIApplication sharedApplication] delegate];// Do any additional setup after loading the view, typically from a nib.}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}- (IBAction)Add:(id)sender {Entity *entry = (Entity *)[NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:self.myDelegate.managedObjectContext];[entry setTitle:self.titleText.text];[entry setBody:self.contentText.text];[entry setNo:self.noText.text];[entry setCreationDate:[NSDate date]];NSError *error;    //托管对象准备好后,调用托管对象上下文的save方法将数据写入数据库    BOOL isSaveSuccess = [self.myDelegate.managedObjectContext save:&error];    if (!isSaveSuccess) {        NSLog(@"Error: %@,%@",error,[error userInfo]);    }else {        NSLog(@"Save successful!");    }}- (IBAction)query:(id)sender {//创建取回数据请求    NSFetchRequest *request = [[NSFetchRequest alloc] init];//设置要检索哪种类型的实体对象    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity"inManagedObjectContext:self.myDelegate.managedObjectContext];//设置请求实体    [request setEntity:entity];//指定对结果的排序方式    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"no"ascending:NO];    NSArray *sortDescriptions = [[NSArray alloc]initWithObjects:sortDescriptor, nil];[request setSortDescriptors:sortDescriptions];NSError *error = nil;    //执行获取数据请求,返回数组    NSMutableArray *mutableFetchResult = [[self.myDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];    if (mutableFetchResult == nil) {        NSLog(@"Error: %@,%@",error,[error userInfo]);    }    self.entries = mutableFetchResult;    NSLog(@"The count of entry:%lu",(unsigned long)[self.entries count]);    for (Entity *entry in self.entries) {        NSLog(@"Title:%@---Content:%@---Date:%@----%@",entry.title,entry.body,entry.creationDate,entry.no);_titleText.text = entry.title;_contentText.text = entry.body;_noText.text = entry.no;    }}@end

0 0