ios中的coredata的使用

來源:互聯網
上載者:User

標籤:

本文轉載至 http://m.blog.csdn.net/blog/chen505358119/9334831

 

Core Data資料持久化是對SQLite的一個升級,它是ios整合的,在說Core Data之前,我們先說說在CoreData中使用的幾個類。

   (1)NSManagedObjectModel(被管理的物件模型)

           相當於實體,不過它包含 了實體間的關係

    (2)NSManagedObjectContext(被管理的物件內容)

         操作實際內容

        作用:插入資料  查詢  更新  刪除

  (3)NSPersistentStoreCoordinator(持久化儲存助理)

          相當於資料庫的連接器

    (4)NSFetchRequest(擷取資料的請求)    

        相當於查詢語句

     (5)NSPredicate(相當於查詢條件)

    (6)NSEntityDescription(實體結構)

    (7)尾碼名為.xcdatamodel的包

        裡面的.xcdatamodel檔案,用資料模型編輯器編輯

       編譯後為.momd或.mom檔案,這就是為什麼檔案中沒有這個東西,而我們的程式中用到這個東西而不會報錯的原因

   首先我們要建立模型對象

   

  其次我們要產生模型對象的實體User,它是繼承NSManagedObjectModel的

  

    點擊之後你會發現它會自動的產生User,現在主要說一下,產生的User對象是這種形式的

 

這裡解釋一下dynamic  平常我們接觸的是synthesize

 dynamic和synthesize有什麼區別呢?它的setter和getter方法不能自已定義

 

開啟CoreData的SQL語句輸出開關

1.開啟Product,點擊EditScheme...
2.點擊Arguments,在ArgumentsPassed On Launch中添加2項
1> -com.apple.CoreData.SQLDebug
2> 1

 

 

#import <UIKit/UIKit.h>#import <CoreData/CoreData.h>@class ViewController;@interface AppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;@property (strong, nonatomic) ViewController *viewController;@property(strong,nonatomic,readonly)NSManagedObjectModel* managedObjectModel;@property(strong,nonatomic,readonly)NSManagedObjectContext* managedObjectContext;@property(strong,nonatomic,readonly)NSPersistentStoreCoordinator* persistentStoreCoordinator;@end

 

#import "AppDelegate.h"#import "ViewController.h"@implementation AppDelegate@synthesize managedObjectModel=_managedObjectModel;@synthesize managedObjectContext=_managedObjectContext;@synthesize persistentStoreCoordinator=_persistentStoreCoordinator;- (void)dealloc{    [_window release];    [_viewController release];    [_managedObjectContext release];    [_managedObjectModel release];    [_persistentStoreCoordinator release];    [super dealloc];}- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];    // Override point for customization after application launch.    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];    self.window.rootViewController = self.viewController;    [self.window makeKeyAndVisible];    return YES;}- (void)applicationWillResignActive:(UIApplication *)application{    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.}- (void)applicationDidEnterBackground:(UIApplication *)application{    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.}- (void)applicationWillEnterForeground:(UIApplication *)application{    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.}- (void)applicationDidBecomeActive:(UIApplication *)application{    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.}- (void)applicationWillTerminate:(UIApplication *)application{    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.}//託管對象-(NSManagedObjectModel *)managedObjectModel{    if (_managedObjectModel!=nil) {        return _managedObjectModel;    }//    NSURL* modelURL=[[NSBundle mainBundle] URLForResource:@"CoreDataExample" withExtension:@"momd"];//    _managedObjectModel=[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];    _managedObjectModel=[[NSManagedObjectModel mergedModelFromBundles:nil] retain];    return _managedObjectModel;}//託管物件內容-(NSManagedObjectContext *)managedObjectContext{    if (_managedObjectContext!=nil) {        return _managedObjectContext;    }        NSPersistentStoreCoordinator* coordinator=[self persistentStoreCoordinator];    if (coordinator!=nil) {        _managedObjectContext=[[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];                [_managedObjectContext setPersistentStoreCoordinator:coordinator];    }    return _managedObjectContext;}//持久化儲存協調器-(NSPersistentStoreCoordinator *)persistentStoreCoordinator{    if (_persistentStoreCoordinator!=nil) {        return _persistentStoreCoordinator;    }//    NSURL* storeURL=[[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreaDataExample.CDBStore"];//    NSFileManager* fileManager=[NSFileManager defaultManager];//    if(![fileManager fileExistsAtPath:[storeURL path]])//    {//        NSURL* defaultStoreURL=[[NSBundle mainBundle] URLForResource:@"CoreDataExample" withExtension:@"CDBStore"];//        if (defaultStoreURL) {//            [fileManager copyItemAtURL:defaultStoreURL toURL:storeURL error:NULL];//        }//    }    NSString* docs=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];    NSURL* storeURL=[NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"CoreDataExample.sqlite"]];    NSLog(@"path is %@",storeURL);    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;}//-(NSURL *)applicationDocumentsDirectory//{//    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];//}@end

 

#import <UIKit/UIKit.h>#import "AppDelegate.h"@interface ViewController : UIViewController@property (retain, nonatomic) IBOutlet UITextField *nameText;@property (retain, nonatomic) IBOutlet UITextField *ageText;@property (retain, nonatomic) IBOutlet UITextField *sexText;@property(nonatomic,retain)AppDelegate* myAppDelegate;- (IBAction)addIntoDataSource:(id)sender;- (IBAction)query:(id)sender;- (IBAction)update:(id)sender;- (IBAction)del:(id)sender;

 

#import "ViewController.h"#import "User.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad{    [super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.    _myAppDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}- (void)dealloc {    [_nameText release];    [_ageText release];    [_sexText release];    [super dealloc];}//插入資料- (IBAction)addIntoDataSource:(id)sender {    User* user=(User *)[NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.myAppDelegate.managedObjectContext];    [user setName:_nameText.text];    [user setAge:[NSNumber numberWithInteger:[_ageText.text integerValue]]];    [user setSex:_sexText.text];    NSError* error;    BOOL isSaveSuccess=[_myAppDelegate.managedObjectContext save:&error];    if (!isSaveSuccess) {        NSLog(@"Error:%@",error);    }else{        NSLog(@"Save successful!");    }    }//查詢- (IBAction)query:(id)sender {    NSFetchRequest* request=[[NSFetchRequest alloc] init];    NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];    [request setEntity:user];//    NSSortDescriptor* sortDescriptor=[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];//    NSArray* sortDescriptions=[[NSArray alloc] initWithObjects:sortDescriptor, nil];//    [request setSortDescriptors:sortDescriptions];//    [sortDescriptions release];//    [sortDescriptor release];    NSError* error=nil;    NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];    if (mutableFetchResult==nil) {        NSLog(@"Error:%@",error);    }    NSLog(@"The count of entry: %i",[mutableFetchResult count]);    for (User* user in mutableFetchResult) {        NSLog(@"name:%@----age:%@------sex:%@",user.name,user.age,user.sex);    }    [mutableFetchResult release];    [request release];}//更新- (IBAction)update:(id)sender {    NSFetchRequest* request=[[NSFetchRequest alloc] init];    NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];    [request setEntity:user];    //查詢條件    NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"chen"];    [request setPredicate:predicate];    NSError* error=nil;    NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];    if (mutableFetchResult==nil) {        NSLog(@"Error:%@",error);    }    NSLog(@"The count of entry: %i",[mutableFetchResult count]);    //更新age後要進行儲存,否則沒更新    for (User* user in mutableFetchResult) {        [user setAge:[NSNumber numberWithInt:12]];            }    [_myAppDelegate.managedObjectContext save:&error];    [mutableFetchResult release];    [request release];    }//刪除- (IBAction)del:(id)sender {    NSFetchRequest* request=[[NSFetchRequest alloc] init];    NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];    [request setEntity:user];    NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"chen"];    [request setPredicate:predicate];    NSError* error=nil;    NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];    if (mutableFetchResult==nil) {        NSLog(@"Error:%@",error);    }    NSLog(@"The count of entry: %i",[mutableFetchResult count]);    for (User* user in mutableFetchResult) {        [_myAppDelegate.managedObjectContext deleteObject:user];    }        if ([_myAppDelegate.managedObjectContext save:&error]) {        NSLog(@"Error:%@,%@",error,[error userInfo]);    }}@end

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.