Core Data浅谈系列之五 : 在UITableView中展示

在逻辑上(表关系)将Team和Player关联起来后,我们将其展现到UI视图上。

首先,为App添加导航栏:

@interface AppDelegate : UIResponder <UIApplicationDelegate >

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UINavigationController *navController;
@property (strong, nonatomic) ViewController *viewController;

@end

@implementation AppDelegate

- (void)dealloc
{
    [_window release];
    [_navController release];
    [_viewController 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.navController = [[[UINavigationController alloc] initWithRootViewController:self.viewController] autorelease];
    self.window.rootViewController = self.navController;
    [self.window makeKeyAndVisible];
    return YES;
}

然后在ViewController上添加一个UITableView,布局好并实现如下相应的代理函数:

#pragma mark -
#pragma mark - UITableView DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.teamArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"TeamTableViewCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (nil == cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier] autorelease];
    }

    Team *teamObject = [self.teamArray objectAtIndex:indexPath.row];
    UIImage *nbaImage = [UIImage imageNamed:@"nba@2x.jpg"];
    cell.imageView.image = nbaImage;
    cell.imageView.backgroundColor = [UIColorredColor];
    cell.textLabel.text = teamObject.name;
    cell.detailTextLabel.text = teamObject.city;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

#pragma mark -
#pragma mark - UITableView Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    Team *teamObject = [self.teamArray objectAtIndex:indexPath.row];
    PlayerListViewController *playerListVC = [[[PlayerListViewController alloc] init] autorelease];
    playerListVC.team = teamObject;
    playerListVC.cdViewController = self;
    [self.navigationController pushViewController:playerListVC animated:YES];
}

在插入一些球队信息后,可以得到如下效果(按球队名称排序):

- (NSArray *)fetchTeamList
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *teamEntity = [NSEntityDescription entityForName:@"Team" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:teamEntity];

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name"ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

    NSError *error = NULL;
    NSArray *array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"Error : %@\n", [error localizedDescription]);
    }

    [fetchRequest release], fetchRequest = nil;

    return array;
}

点击cell,就进入到该队的球员列表:

- (NSArray *)fetchPlayerList
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *teamEntity = [NSEntityDescription entityForName:@"Player" inManagedObjectContext:self.cdViewController.managedObjectContext];
    [fetchRequest setEntity:teamEntity];

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"age"ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"team == %@", self.team];
    [fetchRequest setPredicate:predicate];

    NSError *error = NULL;
    NSArray *array = [self.cdViewController.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"Error : %@\n", [error localizedDescription]);
    }

    [fetchRequest release], fetchRequest = nil;

    return array;
}

通过导航栏右边的Add按钮来添加球员信息:

- (IBAction)addBtnDidClick:(id)sender
{
    // We don't check the user input.
    Player *playerObject = [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:self.cdViewController.managedObjectContext];
    playerObject.name = self.nameTextField.text;
    playerObject.age = [NSNumber numberWithInteger:[self.ageTextField.text integerValue]];
    playerObject.team = self.team;
    [self.cdViewController saveContext];
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)cancelBtnDidClick:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}

以上对NSManagedObject的操作都位于同一份NSManagedObjectContext中。如上面添加球员的函数addBtnDidClick:所注释的,添加球员信息时并没有对数据进行验证 —— 这将在下一篇讨论。

Brief Talk About Core Data Series, Part 5 : Showing in UITableView

Jason Lee @ Hangzhou

Blog : http://blog.csdn.net/jasonblog

Weibo : http://weibo.com/jasonmblog

时间: 2024-09-15 10:07:28

Core Data浅谈系列之五 : 在UITableView中展示的相关文章

Core Data浅谈系列汇总

Core Data浅谈系列之一 : 基础结构 Core Data浅谈系列之二 : 简单的CURD Core Data浅谈系列之三 : 了解NSManagedObject和NSPredicate Core Data浅谈系列之四 : 数据模型的版本变迁 Core Data浅谈系列之五 : 在UITableView中展示 Core Data浅谈系列之六 : 验证用户输入 Core Data浅谈系列之七 : 使用NSFetchedResultsController Core Data浅谈系列之八 : 关

Core Data浅谈系列之十 : 关于数据模型中实体的属性

之前写了<Core Data浅谈系列汇总>,今天稍微回顾了下,做些补充. 在这个系列的第一篇<基础结构>中(2013年1月份的文章,时间过得好快啊!),有简单带过Entity的Attribute: 数据类型.布尔值统一用NSNumber来表示: 字符串类型用NSString表示: 时间类型用NSDate表示: 二进制数据类型用NSData表示: 非标准类型用Transformable来表示: 而Attribute还有其自身的Properties,比如Transient表示不用持久化

Core Data浅谈系列之八 : 关于并发

有时候,我们需要有个worker thread来做一些密集型或者长耗时的任务,以避免阻塞住UI,给用户不好的体验.比如从网络上获取一批数据,然后解析它们,并将其输出到存储文件中.这时候,由于数据层发生了变动,我们希望通知到主线程更新UI -- 这就涉及到Core Data的多线程特性. 比如我们一直以来使用的Demo中,添加球员信息的AddPlayerViewController和显示球员列表的PlayerListViewController在进行CURD操作时都是在主ViewControlle

Core Data浅谈系列之七 : 使用NSFetchedResultsController

上一篇讨论到添加球员信息后,球员列表没有及时得到修改.这是由于之前我们简单地使用了一个NSMutableArray来管理球员列表,需要我们额外做一些变更通知.而在Core Data和UITableView之间,存在这一个名为NSFetchedResultsController的类为我们提供更多方便. 从很大程度上来看,NSFetchedResultsController是为了响应Model层的变化而设计的. 在使用NSFetchedResultsController之前,我们需要为其设置一个NS

Core Data浅谈系列之一 : 基础结构

Core Data是苹果官方提供的一套框架,用来解决与对象生命周期管理.对象关系图管理和持久化等方面相关的问题.大多数情况下,我们引入Core Data作为持久化数据的解决方案,并利用它将持久化数据映射为内存对象. 为什么要使用Core Data呢?以下几点可供参考: 有丰富且良好的文档,方便新手入门.老手埋坑.这些文档多半来源于Apple官方,以及Stackoverflow. 有着经过很多开发者检验的代码,除了省去我们编码的精力,还有着比我们自己编码更好的代码质量. 苹果出品使得它与OS X或

Core Data浅谈系列之二 : 简单的CURD

在上一篇中简单介绍了Core Data Stack,自上而下地对Core Data应用结构有个基本的认识,不过都是理论上的.这里就以上一篇的理论构建起一个可运行的Demo,执行一些简单的增删改查操作. (图片来自Apple) 首先,我们需要建立如上图的栈结构.因此,在ViewController里添加3个属性: @interface ViewController : UIViewController @property (nonatomic, retain) NSManagedObjectMod

Core Data浅谈系列之六 : 验证用户输入

在做Web开发时,需要谨记的一条原则是"绝不要相信用户的任何输入"(参见<Essential PHP Security>). 与网页上的表单提交类似,做客户端开发时也应该考虑用户输入,比如可以为UITextField设置代理处理用户实时输入的内容,也可以读取完用户输入再做检查,或者是NSManagedObject的验证功能. 比如,我们可以在Player的实现里提供验证函数:  #define PLAYER_ERROR_DOMAIN @"PLAYER_ERROR_

Core Data浅谈系列之九 : 使用Mapping Model

通常,我们都会尽量使数据模型的变化尽量简单.但有些情况下,不得不进行大的改动,甚至是重新设计数据模型.在这种情况下,之前提过的简单数据迁移已经无法适应了,需要引入Mapping Model这个中间层. 这时,又想起之前提过的一句话: There is no problem in computer science that can't be solved by adding another level of indirection. 这里做一个简单的变动,先为球员增加薪水属性:  然后创建一名球员

Core Data浅谈系列之四 : 数据模型的版本变迁

继上一篇文章末尾提到的,一支队伍可以添加多名球员,不过一名球员只能属于一支队伍中,这分别对应着Core Data中一对多和一对一的属性关系: 如上两图,是在Team实体里面添加了一个players关系,指向Player实体,可以一支球队关联多名球员,并且最多只允许关联15名球员. 同样地,也为Player实体添加team关系,指向Team实体: 一名球员只能关联一支球队,并且让这个关系成双向的,即一个Player对象属于某支球队时,该球队的players属性就自动关联该Player对象. 做完以