【问题标题】:Displaying Coredata in UITableView在 UITableView 中显示 Coredata
【发布时间】:2013-06-14 14:09:03
【问题描述】:

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

【问题讨论】:

    标签: ios uitableview core-data


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      【讨论】:

      • 我也按照您链接我的教程进行了操作,一切顺利,在我运行它之前没有错误。我''在 tagviewcontrollers.m/.h 中更新我的代码,抛出的错误是......由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'+entityForName:nil 不是搜索实体名称的合法 NSManagedObjectContext 参数'音乐''
      • 就像错误说 entityForName 不能为零。实体的名称是您在数据模型文件 (xcdatamodeld) 中拥有的模型的名称。假设您有许多模型,并且 NSFetchResults 需要知道您要获取哪些实体。所以你给模型的名字作为参数。
      • 所以在我的 xcdatamodeld (称为 Music.xcdatamodeld )中我有实体 Music 具有 3 个属性专辑、艺术家和名称,我认为这需要有 [NSEntityDescription entityForName:@"Music" inManagedObjectContext:self 。语境];不正确吗?
      • 是的,它是正确的。确保上下文不为零。也许这可以解决您的下一个问题:stackoverflow.com/questions/11596487/…
      • 所以我需要通过添加 CoreDataHelper *appDelegate = (CoreDataHelper *)[[UIApplication sharedApplication]delegate]; context = [appDelegate context]; 从 coredatahelper 中定义的位置导入上下文
      【解决方案3】:
      - (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;
       }
      

      【讨论】:

      • 1) 当 NSFetchedResultsController 做得更好时,为什么要手动执行。 2)不要从 AppDelegate 获取 managedObjectContext,将它传递给控制器​​堆栈(每当我看到从 AppDelegate 中提取 moc 的代码时,它只会尖叫“新手”) 3)检查获取的请求的返回值。只有当它为 nil 时,您才应该检查错误参数。因为只有在方法返回 nil 时才保证有效。
      • 我已经使用 NSFetchedResults 更新了我的代码并收到以下错误 *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“+entityForName:nil 不是搜索实体的合法 NSManagedObjectContext 参数名称“音乐”
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多