要用 CoreData 结合 UITableView 使用

本文详细介绍如何利用CoreData框架结合UITableView实现数据自动更新。包括创建CoreData模型、配置AppDelegate中的CoreData堆栈、实现数据读取及更新,并通过NSFetchedResultsController监听数据库变化以实时更新UITableView。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近几天学了 coreData 结合 UITableView 使用,自动更新内容.

下面是基础的内容

创建 coreData :


新建—> Core Data-> Data Model 创建

点击产生的 Model.xcdatamodeld -> Add Entity 然后添加属性(attribute)


产生文件coreData 文件:选中 Model.xcdatamodeld ->点击左上方的 Editor—>Create NSManagerObject subclass ,会创建四个文件,然后就创建完成了,接下来写代码


为了获得 NSManagedObjectContext  context  

AppDelegate中写很多代码,,(这些代码是根据Model.xcdatamodeld来获得 context, 必要的 但一般框架都不用我们自己写的),是为了创建一个 sqlite ,因为 coredata 本身就是去管理 sqlite 的,把两者连接起来即可..我不太看得懂AppDelegate中写的这些代码委屈,求大神指教啊

//

//  AppDelegate.m

//  coreDataTest

//

//  Created by tarena on 16/1/7.

//  Copyright © 2016 tarena. All rights reserved.

//


#import "AppDelegate.h"

#import <CoreData/CoreData.h>

@interface AppDelegate ()


@end


@implementation AppDelegate



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    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:.

     [self saveContext];

}


#pragma mark - Core Data stack


@synthesize managedObjectContext = _managedObjectContext;

@synthesize managedObjectModel = _managedObjectModel;

@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;


- (NSURL *)applicationDocumentsDirectory {

    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.tarena.Demo02_CoreData_Auto" in the application's documents directory.

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

}


- (NSManagedObjectModel *)managedObjectModel {

    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.

    if (_managedObjectModel != nil) {

        return _managedObjectModel;

    }

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];

    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return _managedObjectModel;

}


- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.

    if (_persistentStoreCoordinator != nil) {

        return _persistentStoreCoordinator;

    }

    

    // Create the coordinator and store

    

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Model.sqlite"];

    NSError *error = nil;

    NSString *failureReason = @"There was an error creating or loading the application's saved data.";

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        // Report any error we got.

        NSMutableDictionary *dict = [NSMutableDictionary dictionary];

        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";

        dict[NSLocalizedFailureReasonErrorKey] = failureReason;

        dict[NSUnderlyingErrorKey] = error;

        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];

        // Replace this with code to handle the error appropriately.

        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

        abort();

    }

    

    return _persistentStoreCoordinator;

}


- (NSManagedObjectContext *)managedObjectContext {

    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)

    if (_managedObjectContext != nil) {

        return _managedObjectContext;

    }

    

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (!coordinator) {

        return nil;

    }

    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];

    [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    return _managedObjectContext;

}


#pragma mark - Core Data Saving support


- (void)saveContext {

    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;

    if (managedObjectContext != nil) {

        NSError *error = nil;

        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {

            // Replace this implementation with code to handle the error appropriately.

            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

            abort();

        }

    }

}


@end




然后就是在控制器中写

//上下文

@property (nonatomic,strong) NSManagedObjectContext *context;

//结果控制器

@property (nonatomic,strong) NSFetchedResultsController *resultController;

//懒加载

-(NSManagedObjectContext *)context{

    if (!_context) {

//从 Delegate 中获得 context

        AppDelegate *delegate = [UIApplicationsharedApplication].delegate;

        _context = delegate.managedObjectContext;

    }

    return_context;

}


- (NSFetchedResultsController *)resultController {

    if(_resultController ==nil) {

        NSFetchRequest *request = [NSFetchRequestfetchRequestWithEntityName:@"PersonEntity"];

        //排序描述算子

        NSSortDescriptor *sortDescriptor = [NSSortDescriptorsortDescriptorWithKey:@"name"ascending:YES];

        request.sortDescriptors =@[sortDescriptor];

          /** 设置过滤条件 */

        //NSPredicate *pre = [NSPredicate predicateWithFormat:<#(nonnull NSString *), ...#>];

        

        /**

         参数一:请求对象(指定实体)

         参数二:上下文

         参数三:指定分区 section的原则(哪一列;名字一样,同一个分区;)

         参数四:指定缓存结果的文件夹的名字

         */

        _resultController = [[NSFetchedResultsControlleralloc] initWithFetchRequest:requestmanagedObjectContext:self.contextsectionNameKeyPath:@"name"cacheName:@"CacheName"];

        _resultController.delegate =self;

        //执行 request (具有监听的能力)

        NSError *error =nil;

        if (![_resultControllerperformFetch:&error]) {//这句一定要写

            NSLog(@"执行监听请求失败");

        }

    }

    return_resultController;

}

然后就是设置 tableView 的三问

#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return1;

    

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

     returnself.resultController.fetchedObjects.count;;

}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:@"Cell"forIndexPath:indexPath];

    PersonEntity *person =self.resultController.fetchedObjects[indexPath.row];

    cell.textLabel.text = person.name;

    //cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",person.age];

    return cell;

}

明确:

1. 结果控制器只是监听/显示数据库中的数据

2. 只有上下文对象才能对数据进行操作(增/删/改/查)

3. 从结果控制器对象获取上下文对象


这样你添加一个,界面上就多一个 

明天再写 在此基础上的增,删...




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值