使用 Core Data 将数据显示到表格(不使用.xib 文件)

本文详细介绍如何在iOS应用中利用CoreData进行数据持久化管理,包括创建实体模型、搭建视图控制器及实现数据增删改查等功能。

1.新建一个使用Core Data 的Project

2.在 Core_Data____.xcdatamodeld 文件中创建一个 Person 实体和 Person 类的三个属性 age,firstName,lastName,如下:



3.将创建的Person类实例化为类文件,

(1)创建一个新文件,如图,


(2)这一步做完后,Xcode就会为你创建好一个Person.h 和一个Person.m 文件。

4.你工程里,创建两个视图控制器,两个都是UIViewController的子类,分别命名为PersonListViewControllerAddPersonViewController。创建的这两个视图控制器时不带Xib文件的(我们不需要Interface Builder,因为我们UI很简单)。 

5.设置PersonListViewController为根控制器,在AppDelegate.h 和 AppDelegate.m 文件中做如下修改:

AppDelegate.h

@property (nonatomic,strong) PersonListViewViewController *personListViewController;
@property (nonatomic, strong) UINavigationController *navigationController;

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    self.personListViewController = [[PersonListViewViewController alloc] initWithNibName:nil bundle:nil];
    self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.personListViewController];
    
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    self.window.rootViewController = self.navigationController;
    
    return YES;
}

6.接下来就是PersonListViewControllerAddPersonViewController文件的实现,代码也不是特别难看懂,就直接贴上来了。

PersonListViewController.h

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface PersonListViewViewController : UIViewController<UITableViewDelegate,UITableViewDataSource,NSFetchedResultsControllerDelegate>

@property(nonatomic, strong) UITableView *tableViewPersons;
@property(nonatomic, strong) UIBarButtonItem *barButtonAddPerson;
@property(nonatomic, strong) NSFetchedResultsController *personsFRC;

@end

PersonListViewController.m

#import "PersonListViewViewController.h"
#import "AddPersonViewController.h"
#import "AppDelegate.h"
#import "Person.h"

@interface PersonListViewViewController ()

@end

@implementation PersonListViewViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self != nil) {
        //Create the fetch request first
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        
        //Here is the entity whose contents we want to read
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:[self managedObjectContext]];
        NSSortDescriptor *ageSort = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
        NSSortDescriptor *firstNameSort = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:ageSort,firstNameSort, nil];
        fetchRequest.sortDescriptors = sortDescriptors;
        
        //Tell the request that we want to read the contents of Person entity
        [fetchRequest setEntity:entity];
        self.personsFRC = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[self managedObjectContext] sectionNameKeyPath:nil cacheName:nil];
        self.personsFRC.delegate = self;
        NSError *fetchingError = nil;
        if ([self.personsFRC performFetch:&fetchingError]) {
            NSLog(@"Successfully fetched.");
        }else{
            NSLog(@"Failed to fetch.");
        }
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    self.title = @"Persons";
    self.tableViewPersons = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableViewPersons.delegate = self;
    self.tableViewPersons.dataSource = self;
    [self.view addSubview:self.tableViewPersons];
    self.barButtonAddPerson = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewPerson:)];
    [self.navigationItem setLeftBarButtonItem:[self editButtonItem] animated:NO];
    [self.navigationItem setRightBarButtonItem:self.barButtonAddPerson animated:NO];
}

- (void)addNewPerson:(id)paramSender{
    AddPersonViewController *controller = [[AddPersonViewController alloc] initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:controller animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    id<NSFetchedResultsSectionInfo> sectionInfo = [self.personsFRC.sections objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *result = nil;
    static NSString *PersonTableViewCell = @"PersonTableViewCell";
    result = [tableView dequeueReusableCellWithIdentifier:PersonTableViewCell];
    if (result == nil) {
        result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PersonTableViewCell];
        result.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    Person *person = [self.personsFRC objectAtIndexPath:indexPath];
    result.textLabel.text = [person.firstName stringByAppendingFormat:@".%@",person.lastName];
    result.detailTextLabel.text = [NSString stringWithFormat:@"Age:%lu",(unsigned long)[person.age unsignedIntegerValue]];
    return result;
    
}

-(NSManagedObjectContext *)managedObjectContext{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
    return managedObjectContext;
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
    [self.tableViewPersons reloadData];
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Person *personToDelete = [self.personsFRC objectAtIndexPath:indexPath];
    
    /*VERY IMPORTANT: we need to make sure we are not reloading the table view while deleting the managed object*/
    self.personsFRC.delegate = self;
    [[self managedObjectContext] deleteObject:personToDelete];
    if ([personToDelete isDeleted]) {
        NSError *savingError = nil;
        
        if ([[self managedObjectContext] save:&savingError]) {
            NSError *fetchingError = nil;
            if ([self.personsFRC performFetch:&fetchingError]) {
                NSLog(@"Successfully fetched.");
                NSArray *rowsToDelegate = [[NSArray alloc] initWithObjects:indexPath, nil];
                [_tableViewPersons deleteRowsAtIndexPaths:rowsToDelegate withRowAnimation:UITableViewRowAnimationAutomatic];
            }else{
                NSLog(@"Failed to fetch with error = %@",fetchingError);
            }
        }else{
            NSLog(@"Failed to save the context with error = %@",savingError);
        }
    }
    self.personsFRC.delegate = self;
}


-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    if (editing) {
        [self.navigationItem setRightBarButtonItem:nil animated:YES];
    }else{
        [self.navigationItem setRightBarButtonItem:self.barButtonAddPerson animated:YES];
    }
    [self.tableViewPersons setEditing:editing animated:YES];
}

@end



AddPersonViewController.h

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface AddPersonViewController : UIViewController

@property(nonatomic,strong)UITextField *textFieldFirstName;
@property(nonatomic,strong)UITextField *textFieldLastName;
@property(nonatomic,strong)UITextField *textFieldAge;
@property(nonatomic,strong)UIBarButtonItem *barButtonAdd;

@end

AddPersonViewController.m

#import "AddPersonViewController.h"
#import "AppDelegate.h"
#import "Person.h"

@interface AddPersonViewController ()

@end

@implementation AddPersonViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    self.title = @"New Person";
    CGRect textFieldRect = CGRectMake(20.0f, 80.0f, self.view.bounds.size.width - 40.0f, 31.0f);
    self.textFieldFirstName = [[UITextField alloc] initWithFrame:textFieldRect];
    self.textFieldFirstName.placeholder = @"First Name";
    self.textFieldFirstName.borderStyle = UITextBorderStyleRoundedRect;
    self.textFieldFirstName.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.textFieldFirstName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [self.view addSubview:self.textFieldFirstName];
    textFieldRect.origin.y += 37.0f;
    self.textFieldLastName = [[UITextField alloc] initWithFrame:textFieldRect];
    self.textFieldLastName.placeholder = @"Last Name";
    self.textFieldLastName.borderStyle = UITextBorderStyleRoundedRect;
    self.textFieldLastName.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.textFieldLastName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [self.view addSubview:self.textFieldLastName];
    textFieldRect.origin.y += 37.0f;
    self.textFieldAge = [[UITextField alloc] initWithFrame:textFieldRect];
    self.textFieldAge.placeholder = @"Age";
    self.textFieldAge.borderStyle = UITextBorderStyleRoundedRect;
    self.textFieldAge.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.textFieldAge.keyboardType = UIKeyboardTypeNumberPad;
    self.textFieldAge.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [self.view addSubview:self.textFieldAge];
    self.barButtonAdd = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:self action:@selector(createNewPerson:)];
    [self.navigationItem setRightBarButtonItem:self.barButtonAdd animated:NO];
}

-(void)createNewPerson:(id)paramSender{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
    Person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext];
    if (newPerson != nil) {
        newPerson.firstName = self.textFieldFirstName.text;
        newPerson.lastName = self.textFieldLastName.text;
        newPerson.age = [NSNumber numberWithInteger:[self.textFieldAge.text integerValue]];
        NSError *savingError = nil;
        if ([managedObjectContext save:&savingError]) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            NSLog(@"Failed to save the managed object context.");
        }
    }else{
        NSLog(@"Failed to create the new person object.");
    }
}


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.textFieldFirstName becomeFirstResponder];
}

@end


7.运行结果:


多角色体系 支持管理员、商家、消费者三种角色,权限分级管控: 管理员:负责平台整体配置、用户审核、数据监控等全局操作。 商家:管理店铺信息、发布商品、处理订单、回复评价等。 消费者:浏览商品、加入购物车、下单支付、评价商品等。 实现用户注册(手机号 / 邮箱验证)、登录(支持密码 / 验证码 / 第三方登录)、个人信息管理(头像、收货地址、密码修改)。 权限精细化控制 商家仅能管理自家店铺及商品,消费者仅能查看和购买商品,管理员拥有全平台数据访问权限。 二、商品管理功能 商品信息维护 商家可发布商品:填写名称、分类(如服饰、电子产品)、子类别(如手机、笔记本)、规格(尺寸、颜色、型号)、价格、库存、详情描述(图文)、物流信息(运费、发货地)等。 支持商品上下架、库存调整、信息编辑,系统自动记录商品状态变更日志。 商品分类与搜索 按多级分类展示商品(如 “数码产品→手机→智能手机”),支持自定义分类体系。 提供智能搜索功能:按关键词(名称、品牌)搜索,支持模糊匹配和搜索联想;结合用户浏览历史对搜索结果排序(优先展示高相关度商品)。 商品推荐 基于用户浏览、收藏、购买记录,推荐相似商品(如 “浏览过该商品的用户还买了…”)。 首页展示热门商品(销量 TOP10)、新品上架、限时折扣等推荐列。 三、订单与交易管理 购物车与下单 消费者可将商品加入购物车,支持修改数量、选择规格、移除商品,系统自动计算总价(含运费、折扣)。 下单流程:确认收货地址→选择支付方式(在线支付、货到付款)→提交订单→系统生成唯一订单号。 订单处理流程 订单状态跟踪:待支付→已支付→商家发货→物流运输→消费者收货→订单完成,各状态变更实时通知用户。 商家端功能:查看新订单提醒、确认发货(填写物流单号)、处理退款申请(需审核理由)。 消费者端功能:查看订单详情、追踪物流、申请退款 / 退货、确认收货。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值