亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

iOS App中數(shù)據(jù)管理框架Core Data的基本數(shù)據(jù)操作教程

 更新時間:2016年06月28日 09:46:05   作者:琿少  
Core Data框架能夠為我們提供比操作SQL關(guān)系型數(shù)據(jù)庫更簡單的數(shù)據(jù)管理方式,而且內(nèi)置于Xcode中配合IDE操作十分方便,下面我們就來看一下iOS App中數(shù)據(jù)管理框架Core Data的基本數(shù)據(jù)操作教程

NSEntityDescription是實體描述對象,它可以類比如數(shù)據(jù)庫中的表,NSEntityDescription存放的是表的結(jié)構(gòu)信息。這些類都是一些抽象的結(jié)構(gòu)類,并不存儲實際每條數(shù)據(jù)的信息,具體的數(shù)據(jù)由NSManagedObject類來描述,我們一般會將實體類化繼承于NSManagedObject。

Xocde工具提供了快捷的實體類化功能,還拿我們一開始創(chuàng)建的班級與學(xué)生實體來演示,點擊.xcdatamodeld文件,點擊Xcode工具上方導(dǎo)航欄的Editor標(biāo)簽,選擇Creat NSManagedObject Subclass選項,在彈出的窗口中勾選要類化的實體,如下圖:

201662893746411.png (320×266)

201662893807952.png (446×396)

這時,Xcode會自動為我們創(chuàng)建一個文件,這些文件中有各個類中屬性的聲明。

一、創(chuàng)建一條數(shù)據(jù)

使用如下代碼進行數(shù)據(jù)的創(chuàng)建:

    //讀取數(shù)據(jù)模型文件
    NSURL *modelUrl = [[NSBundle mainBundle]URLForResource:@"Model" withExtension:@"momd"];
    //創(chuàng)建數(shù)據(jù)模型
    NSManagedObjectModel * mom = [[NSManagedObjectModel alloc]initWithContentsOfURL:modelUrl];
    //創(chuàng)建持久化存儲協(xié)調(diào)者
    NSPersistentStoreCoordinator * psc = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:mom];
    //數(shù)據(jù)庫保存路徑
    NSURL * path =[NSURL fileURLWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"CoreDataExample.sqlite"]];
    //為持久化協(xié)調(diào)者添加一個數(shù)據(jù)接收棧
    /*
    可以支持的類型如下:
     NSString * const NSSQLiteStoreType;//sqlite
     NSString * const NSXMLStoreType;//XML
     NSString * const NSBinaryStoreType;//二進制
     NSString * const NSInMemoryStoreType;//內(nèi)存
    */
    [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:path options:nil error:nil];
    //創(chuàng)建數(shù)據(jù)管理上下文
    NSManagedObjectContext * moc = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
    //關(guān)聯(lián)持久化協(xié)調(diào)者
    [moc setPersistentStoreCoordinator:psc];
    //創(chuàng)建數(shù)據(jù)對象
    /*
    數(shù)據(jù)對象的創(chuàng)建是通過實體名獲取到的
    */
    SchoolClass * modelS = [NSEntityDescription insertNewObjectForEntityForName:@"SchoolClass" inManagedObjectContext:moc];
    //對數(shù)據(jù)進行設(shè)置
    modelS.name = @"第一班";
    modelS.stuNum = @60;
    //進行存儲
    if ([moc save:nil]) {
        NSLog(@"新增成功");
    }
    NSLog(@"%@",[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"CoreDataExample.sqlite"]);
找到在打印出的路徑,會發(fā)現(xiàn)里面多了一個sqlite文件,其中有一張表中添加進了一條數(shù)據(jù)。

二、查詢數(shù)據(jù)

CoreData中通過查詢請求來對數(shù)據(jù)進行查詢操作,查詢請求由NSFetchRequest來進行管理和維護。

NSFetchRequest主要提供兩個方面的查詢服務(wù):

1.提供范圍查詢的相關(guān)功能

2.提供查詢結(jié)果返回類型與排序的相關(guān)功能

NSFetchRequest中常用方法如下:

//創(chuàng)建一個實體的查詢請求 可以理解為在某個表中進行查詢
+ (instancetype)fetchRequestWithEntityName:(NSString*)entityName;
//查詢條件
@property (nullable, nonatomic, strong) NSPredicate *predicate;
//數(shù)據(jù)排序
@property (nullable, nonatomic, strong) NSArray<NSSortDescriptor *> *sortDescriptors;
//每次查詢返回的數(shù)據(jù)條數(shù)
@property (nonatomic) NSUInteger fetchLimit;
//設(shè)置查詢到數(shù)據(jù)的返回類型
/*
typedef NS_OPTIONS(NSUInteger, NSFetchRequestResultType) {
    NSManagedObjectResultType  = 0x00,
    NSManagedObjectIDResultType  = 0x01,
    NSDictionaryResultType          NS_ENUM_AVAILABLE(10_6,3_0) = 0x02,
    NSCountResultType    NS_ENUM_AVAILABLE(10_6,3_0) = 0x04
};
*/
@property (nonatomic) NSFetchRequestResultType resultType;
//設(shè)置查詢結(jié)果是否包含子實體
@property (nonatomic) BOOL includesSubentities;
//設(shè)置要查詢的屬性值
@property (nullable, nonatomic, copy) NSArray *propertiesToFetch;
在SchoolClass實體中查詢數(shù)據(jù),使用如下的代碼:

    //創(chuàng)建一條查詢請求
    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"SchoolClass"];
    //設(shè)置條件為 stuNum=60的數(shù)據(jù)
    [request setPredicate:[NSPredicate predicateWithFormat:@"stuNum == 60"]];
    //進行查詢操作
    NSArray * res = [moc executeFetchRequest:request error:nil];
    NSLog(@"%@",[res.firstObject stuNum]);

進行數(shù)據(jù)初始化

    NSFetchedResultsController的初始化需要一個查詢請求和一個數(shù)據(jù)操作上下文。代碼示例如下:

//遵守協(xié)議
@interface ViewController ()<NSFetchedResultsControllerDelegate>
{
    //數(shù)據(jù)橋接對象
    NSFetchedResultsController * _fecCon;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //進行初始化操作
    NSURL *modelUrl = [[NSBundle mainBundle]URLForResource:@"Model" withExtension:@"momd"];
    NSManagedObjectModel * mom = [[NSManagedObjectModel alloc]initWithContentsOfURL:modelUrl];
    NSPersistentStoreCoordinator * psc = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:mom];
    NSURL * path =[NSURL fileURLWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"CoreDataExample.sqlite"]];
    [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:path options:nil error:nil];
    NSManagedObjectContext * moc = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
    [moc setPersistentStoreCoordinator:psc];
    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"SchoolClass"];
    //設(shè)置數(shù)據(jù)排序
    [request setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"stuNum" ascending:YES]]];
    //進行數(shù)據(jù)橋接對象的初始化
    _fecCon = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:moc sectionNameKeyPath:nil cacheName:nil];
    //設(shè)置代理
    _fecCon.delegate=self;
    //進行數(shù)據(jù)查詢
    [_fecCon performFetch:nil];
}
@end
用于初始化NSFecthedResultsController的數(shù)據(jù)請求對象必須設(shè)置一個排序規(guī)則。在initWithFetchRequest:managedObjectContext:sectionNameKeyPath:cacheName:方法中,如果設(shè)置第三個參數(shù),則會以第三個參數(shù)為鍵值進行數(shù)據(jù)的分區(qū)。當(dāng)數(shù)據(jù)發(fā)生變化時,將通過代理進行方法的回調(diào)。

三、與UITableView進行數(shù)據(jù)綁定

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cellid"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cellid"];
    }
    //獲取相應(yīng)數(shù)據(jù)模型
    SchoolClass * obj = [_fecCon objectAtIndexPath:indexPath];
    cell.textLabel.text = obj.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"有%@人",obj.stuNum];
    return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [_fecCon sections].count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    id<NSFetchedResultsSectionInfo> info =  [_fecCon sections][section];
    return [info numberOfObjects];
   
}
效果如下:

201662893909721.png (313×583)

四、將數(shù)據(jù)變化映射到視圖

//數(shù)據(jù)將要改變時調(diào)用的方法
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
    //開啟tableView更新預(yù)處理
    [[self tableView] beginUpdates];
}
//分區(qū)數(shù)據(jù)改變時調(diào)用的方法
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
    //判斷行為類型
    switch(type) {
        //插入新分區(qū)
        case NSFetchedResultsChangeInsert:
            [[self tableView] insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
        //刪除分區(qū)
        case NSFetchedResultsChangeDelete:
            [[self tableView] deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
        //移動分區(qū)
        case NSFetchedResultsChangeMove:
        //更新分區(qū)
        case NSFetchedResultsChangeUpdate:
            break;
    }
}
//數(shù)據(jù)改變時回調(diào)的代理
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
    switch(type) {
        //插入數(shù)據(jù)
        case NSFetchedResultsChangeInsert:
            [[self tableView] insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
        //刪除數(shù)據(jù)
        case NSFetchedResultsChangeDelete:
            [[self tableView] deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
        //更新數(shù)據(jù)
        case NSFetchedResultsChangeUpdate:
            [self reloadData];
            break;
        //移動數(shù)據(jù)
        case NSFetchedResultsChangeMove:
            [[self tableView] deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [[self tableView] insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}
//數(shù)據(jù)更新結(jié)束調(diào)用的代理
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [[self tableView] endUpdates];
}

相關(guān)文章

最新評論