在表视图中显示数据

时间:2011-02-18 09:09:31

标签: core-data

我创建了一个包含核心数据的应用程序,但无法在表格视图中显示数据。我正在编写下面的代码,用于获取结果:

#import "RootViewController.h"
#import "DetailViewController.h"
#import "AddViewController.h"
#import "EmployeeDetailsAppDelegate.h"

/*
 This template does not ensure user interface consistency during editing operations in the table view. You must implement appropriate methods to provide the user experience you require.
 */

@interface RootViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
@end



@implementation RootViewController

@synthesize detailViewController, fetchedResultsController, managedObjectContext;
@synthesize array;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {

//  EmployeeDetailsAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];

    self.title = @"Employee Name";
    self.navigationItem.rightBarButtonItem = self.editButtonItem;

    NSMutableArray *tempArr = [[NSMutableArray alloc]initWithCapacity:0];

    if (self.fetchedResultsController) {

        tempArr = self.fetchedResultsController.fetchedObjects;

    }

    self.array = tempArr;

    [super viewDidLoad];

    [tempArr release];
}



- (void)viewWillAppear:(BOOL)animated {

    [self.tableView reloadData];
    [super viewWillAppear:animated];
}


/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
 */
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
 */
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
 */

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape.    
    return YES;
}





#pragma mark -
#pragma mark Add a new object

- (void)insertNewObject:(id)sender {

    AddViewController *add = [[AddViewController alloc]initWithNibName:@"AddViewController" bundle:nil];
    self.modalPresentationStyle = UIModalPresentationFormSheet;
    add.wantsFullScreenLayout = NO;

    [self presentModalViewController:add animated:YES];
    [add release];  
}   


#pragma mark -
#pragma mark Table view data source

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


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if([self.array count])
    {
        return [array count];
    }
    return 1;
}


- (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];
    }

    // Configure the cell.

    [self configureCell:cell atIndexPath:indexPath];

    return cell;
}

-(void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath{

    AddViewController *detail = [fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = detail.empName.text;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        // Delete the managed object.
        NSManagedObject *objectToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath];
        if (self.detailViewController.detailItem == objectToDelete) {
            self.detailViewController.detailItem = nil;
        }

        NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
        [context deleteObject:[fetchedResultsController objectAtIndexPath:indexPath]];

        NSError *error;
        if (![context save:&error]) {
            /*
             Replace this implementation with code to handle the error appropriately.

             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }   
}


- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // The table view should not be re-orderable.
    return NO;
}


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // Set the detail item in the detail view controller.

    detailViewController = [[DetailViewController alloc]initWithStyle:UITableViewStylePlain];
    AddViewController *selectedName = (AddViewController *)[[self fetchedResultsController]objectAtIndexPath:indexPath];
    detailViewController.detail = selectedName;
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}


#pragma mark -
#pragma mark Fetched results controller

- (NSFetchedResultsController *)fetchedResultsController {

    if (fetchedResultsController != nil) {
        return fetchedResultsController;
    }

    /*
     Set up the fetched results controller.
     */
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Details" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];

    // Edit the sort key as appropriate.

    NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"EmployeeName" ascending:NO];
    NSSortDescriptor *idDescriptor = [[NSSortDescriptor alloc] initWithKey:@"EmployeeID" ascending:NO];

    NSMutableArray *sortDescriptors = [[NSMutableArray alloc] initWithObjects:nameDescriptor, idDescriptor, nil];

    self.array = sortDescriptors;
    [fetchRequest setSortDescriptors:sortDescriptors];

    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

    [aFetchedResultsController release];
    [fetchRequest release];
    [nameDescriptor release];
    [sortDescriptors release];

    return fetchedResultsController;
}    


#pragma mark -
#pragma mark Fetched results controller delegate

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView beginUpdates];
}


- (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)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)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView endUpdates];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {

    self.fetchedResultsController = nil;
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;

    self.array = nil;
}


- (void)dealloc {

    [array release];
    [detailViewController release];
    [fetchedResultsController release];
    [managedObjectContext release];

    [super dealloc];
}

@end

问题是我收到以下一行的警告:

    tempArr = self.fetchedResultsController.fetchedObjects;

警告是:“/ Users / theseyam /Desktop / EmployeDetails / Class / ResultViewController.m:43:0 /Users/satyam/Desktop/EmployeeDetails/Classes/RootViewController.m:43:警告:不兼容的Objective-C类型分配'struct NSArray *',期望'struct NSMutableArray *'“

1 个答案:

答案 0 :(得分:1)

只需逐字阅读警告。

您尝试将NSArray分配给需要NSMutableArray的变量。

self.fetchedResultsController.fetchedObjects是一个NSArray
tempArr是一个NSMutableArray


但是如果您使用NSFetchedResultsController,则根本不需要您自己的数据数组。 NSFetchedResultsController为您处理所有数据。

所以也许你想要替换

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if([self.array count])
    {
        return [array count];
    }
    return 1;
}

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

无论如何,您自己的数据源无效。因为您将用于NSFetchedResultsController的sortDescriptor分配给它。

NSMutableArray *sortDescriptors = [[NSMutableArray alloc] initWithObjects:nameDescriptor, idDescriptor, nil];

self.array = sortDescriptors;

通过这样做,我不知道你想要达到什么目的。