在UITableView中显示Coredata

时间:2013-06-18 11:18:48

标签: ios uitableview core-data

我正在尝试创建一个UITable视图来显示通过核心数据保存的数据源。我希望每一行都以其中一个属性命名(在我的例子中是歌曲的名称)。我已经成功地创建了显示数组但不保存数据的表。我认为我需要在tagsviewcontroller中导入列表并将一些代码放入numberofrowsinsection和cellforrowatindex中,但我无法理解苹果文档。 任何帮助都会很棒,如果你需要我发布更多的代码,我可以做到这一点。

我对此很新,我使用标准xcode模板创建了一个Tableviewcontroller,如下所示。

//  TagsViewController.h

#import <UIKit/UIKit.h>

@interface TagsViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegatee>


@property (nonatomic, strong) NSManagedObjectContext *context;
@end

和.m文件

#import "TagsViewController.h"
#import "Music.h"



@interface TagsViewController ()

@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;

@end

@implementation TagsViewController

@synthesize fetchedResultsController=_fetchedResultsController, context=_context;

- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];

// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;

// Uncomment the following line to display an Edit button in the navigation bar for this     view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewWillAppear
{
    [self.tableView reloadData];
}


- (void)viewDidUnload
{
    // Release any properties that are loaded in viewDidLoad or can be recreated lazily.
    self.fetchedResultsController = nil;
}


- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[self.fetchedResultsController sections] count];
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
// Configure the cell to show the book's title
Music *music = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = music.name;
}


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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

// Configure the cell.
[self configureCell:cell atIndexPath:indexPath];
return cell;
}



/*
 Returns the fetched results controller. Creates and configures the controller if     necessary.
 */
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
}

// Create and configure a fetch request with the Book entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Music" inManagedObjectContext:self.context];
[fetchRequest setEntity:entity];


// Create the sort descriptors array.
   // NSSortDescriptor *authorDescriptor = [[NSSortDescriptor alloc] initWithKey:@"author" ascending:YES];
   // NSSortDescriptor *titleDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
   // NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:authorDescriptor, titleDescriptor, nil];
   // [fetchRequest setSortDescriptors:sortDescriptors];

// Create and initialize the fetch results controller.
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.context sectionNameKeyPath:@"artist" cacheName:@"Root"];
_fetchedResultsController.delegate = self;

// Memory management.

return _fetchedResultsController;
}

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
// The fetch controller is about to start sending change notifications, so prepare the table view for updates.
[self.tableView beginUpdates];
}


- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.tableView;

switch(type) {

    case NSFetchedResultsChangeInsert:
        [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
        break;

    case NSFetchedResultsChangeDelete:
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        break;

    case NSFetchedResultsChangeUpdate:
        [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
        break;

    case NSFetchedResultsChangeMove:
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
        break;
}
}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type) {

    case NSFetchedResultsChangeInsert:
        [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
        break;

    case NSFetchedResultsChangeDelete:
        [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
        break;
}
}


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
// The fetch controller has sent all current change notifications, so tell the table view to process all updates.
[self.tableView endUpdates];
}

我知道我必须导入某些文件。我的数据库名为music.xcmod​​eld,有自己的music.h和m文件。

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


  @interface Music : NSManagedObject

 @property (nonatomic, retain) NSString * name;
 @property (nonatomic, retain) NSString * artist;
 @property (nonatomic, retain) NSString * album;

 @end

使用.m文件

 #import "Music.h"


 @implementation Music

 @dynamic name;
 @dynamic artist;
 @dynamic album;

 @end

3 个答案:

答案 0 :(得分:3)

答案 1 :(得分:0)

如果从数组或核心数据显示,则没有区别。只需在视图控制器加载时查询核心数据并将结果添加到数组中。然后你知道如何处理一组数据。

在索引行的单元格中,您将从数组中拉出每个对象,并将您想要的任何内容添加到单元格中

答案 2 :(得分:-1)

- (void)viewDidLoad
 {
[super viewDidLoad];

arrData = [[NSMutabaleArray alloc]init];

NSManagedObjectContext *context = //Get it from AppDelegate

NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Music"];

NSError *error = nil;

arrData = [[context executeFetchRequest:request error:&error]mutablecopy];

if (error != nil) {

   //Deal with failure
}
else {

   //Deal with success
}
 // Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
 }

表格视图

#pragma mark - Table view data source

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

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
 {
     return arrData.count;
 }

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
Music *obj = [arrData objectAtindex:indexPath.row];
cell.textLabel.text = obj. name;
// Configure the cell...

return cell;
 }