iOS開發,ios開發教程

來源:互聯網
上載者:User

iOS開發,ios開發教程
Core Data

Core Data是iOS5之後才出現的一個架構,它提供了對象-關係映射(ORM)的功能,即能夠將OC對象轉化成資料,儲存在SQLite資料庫檔案中,也能夠將儲存在資料庫中的資料還原成OC對象。在此資料操作期間,我們不需要編寫任何SQL語句,這個有點類似於著名的Hibernate持久化架構,不過功能肯定是沒有Hibernate強大的。

傳統的資料庫要把資料寫到資料庫,而且要寫SQL語句 Core Data 就避免了寫SQL語句的麻煩了

CoreData的使用步驟

1.建立模型檔案 相當於資料庫 
2.添加實體 相當表 
3.建立實體類 相於模型類 
4.產生上下文 關聯模型檔案產生資料庫 
5.儲存對象到資料庫 
6.從資料庫擷取對象 
7.更新資料 
8.刪除資料

1.建立模型檔案 
所謂的建立模型就是間接產生資料庫表 

2.添加實體 

3.建立實體類 
以建立員工實體類為例 

產生上下檔案 關聯模型檔案產生資料庫
 NSManagedObjectContext  _context = [[NSManagedObjectContext alloc] init];    // 模型檔案    NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];    // 持久化儲存調度器    NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];    NSLog(@"%@",doc);    NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];    //資料存放區的類型 資料庫儲存路徑    [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];    _context.persistentStoreCoordinator = store;
 儲存對象到資料庫
Employee *employee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];    employee.name = @"zhangsan";    employee.age = @18;    employee.height = @1.89;    [_context save:nil];
開啟CoreData的SQL語句輸出開關
    1.開啟Product,點擊EditScheme...    2.點擊Arguments,在ArgumentsPassed On Launch中添加2項    1> -com.apple.CoreData.SQLDebug    2> 1
CoreData執行個體產生實體類
#import <Foundation/Foundation.h>#import <CoreData/CoreData.h>@interface Employee : NSManagedObject@property (nonatomic, retain) NSString * name;@property (nonatomic, retain) NSNumber * age;@property (nonatomic, retain) NSNumber * height;@end
#import "Employee.h"@implementation Employee@dynamic name;@dynamic age;@dynamic height;@end

import標頭檔架構

#import "ViewController.h"#import <CoreData/CoreData.h>#import "Employee.h"@interface ViewController ()@property(strong,nonatomic)NSManagedObjectContext *context;@end
CoreData模糊查詢
@implementation ViewController#pragma mark 模糊查詢- (IBAction)likeSearcher:(id)sender {    // 查詢    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];    // 過濾    // 1.查詢以wang開頭員工    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"wang"];    // 2.以si 結尾    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"si"];    // 3.名字包含 g    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"g"];    // 4.like 以si結尾    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"li*"];    request.predicate = pre;    //讀取資訊    NSError *error = nil;    NSArray *emps = [self.context executeFetchRequest:request error:&error];    if (!error) {        NSLog(@"emps: %@",emps);        for (Employee *emp in emps) {            NSLog(@"%@ %@ %@",emp.name,emp.age,emp.height);        }    }else{        NSLog(@"%@",error);    }}
CoreData 更新資料
#pragma mark 更新員工資訊- (IBAction)updateEmployee:(id)sender {    // 把wangwu的身高更改成 1.7    // 1.尋找wangwu    NSArray *emps = [self findEmployeeWithName:@"wangwu"];    // 2.更新身高    if (emps.count == 1) {        Employee *emp = emps[0];        emp.height = @1.7;    }    // 3.同步(儲存)到資料    [self.context save:nil];}-(NSArray *)findEmployeeWithName:(NSString *)name{    // 1.尋找員工    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name=%@",name];    request.predicate = pre;    return [self.context executeFetchRequest:request error:nil];}

 

CoreData 刪除資料
#pragma mark 刪除員工- (IBAction)deleteEmployee:(id)sender {    [self deleteEmployeeWithName:@"lisi"];}-(void)deleteEmployeeWithName:(NSString *)name{    // 刪除zhangsan    // 1.尋找到zhangsan    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name=%@",name];    request.predicate = pre;    // 2.刪除zhangsan    NSArray *emps = [self.context executeFetchRequest:request error:nil];    for (Employee *emp in emps) {        NSLog(@"刪除員工的人 %@",emp.name);        [self.context deleteObject:emp];    }    // 3.用context同步下資料庫    //所有的操作暫時都是在記憶體裡,調用save 同步資料庫    [self.context save:nil];}
CoreData 查詢資料
#pragma mark 讀取員工資訊- (IBAction)readEmployee:(id)sender {    //建立一個請求對象 (填入要查詢的表名-實體類)    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];    // 過濾查詢    // 尋找張三 並且身高大於1.8    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name=%@ AND height > %@",@"zhangsan",@(1.8)];//    request.predicate = pre;    //排序 以身高進行升序    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];//    request.sortDescriptors = @[sort];    // 分頁查詢 總共13條資料 每頁顯示5條資料    //第一頁的資料    request.fetchLimit = 5;    request.fetchOffset = 10;    //讀取資訊    NSError *error = nil;    NSArray *emps = [self.context executeFetchRequest:request error:&error];    if (!error) {        NSLog(@"emps: %@",emps);        for (Employee *emp in emps) {            NSLog(@"%@ %@ %@",emp.name,emp.age,emp.height);        }    }else{        NSLog(@"%@",error);    }}#pragma mark 添加員工資訊- (IBAction)addEmployee:(id)sender {    // 建立員工    Employee *emp1 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];    // 設定員工屬性    emp1.name = @"lisi";    emp1.age = @28;    emp1.height = @2.10;    //儲存 - 通過上下文操作    NSError *error = nil;    [self.context save:&error];    if (!error) {        NSLog(@"success");    }else{        NSLog(@"%@",error);    } }
CoreData 建立上下文
-(void)setupContext{    // 1.上下文 關聯Company.xcdatamodeld 模型檔案    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];    // 關聯模型檔案    // 建立一個模型對象    // 傳一個nil 會把 bundle下的所有模型檔案 關聯起來    NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];    // 持久化儲存調度器    NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];    // 儲存資料庫的名字    NSError *error = nil;    // 擷取docment目錄    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];    // 資料庫儲存的路徑    NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];    [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:&error];    context.persistentStoreCoordinator = store;    self.context = context;}-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    // 建立員工    for (int i = 0; i < 10; i++) {        Employee *emp1 = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];        // 設定員工屬性        emp1.name = [NSString stringWithFormat:@"wangwu %d",i];        emp1.age = @(28 + i);        emp1.height = @2.10;        //儲存 - 通過上下文操作        NSError *error = nil;        [self.context save:&error];        if (!error) {            NSLog(@"success");        }else{            NSLog(@"%@",error);        }    }  }@end
調用
- (void)viewDidLoad {    [super viewDidLoad];    // 建立一個資料庫 company.sqlite    // 資料庫要一張表 員工表 (name,age,heigt)    // 往資料添加員工資訊    // CoreData    [self setupContext];}
 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.