2

我正在尝试创建一个 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
4

3 回答 3

0

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

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

于 2013-06-18T11:31:24.990 回答
-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;
 }
于 2013-06-18T11:55:15.683 回答