2016-03-20 7 views
0

Я хотел бы объяснить наиболее подробную проблему, с которой я столкнулся. Раньше вместо UIViewController у меня был UITableViewController, проблема в том, что теперь мне нужно показать больше контента в представлении, которое просто в виде таблицы, поэтому я создал новое представление. Теперь у меня есть UIViewController, который имеет: UIScrollView. Оборудовано: 1. UIView + 1 UITableViewCoreData + UIViewController + UITableView

Я использую AutoLayout. И работает нормально. Проблема, с которой я сталкиваюсь, заключается в том, что, поскольку я переключился на использование этого представления, я не могу отображать содержимое в таблице с помощью coredata. Я смог сделать это без coredata, но не с этим. В interfacebuilder я устанавливаю datasource и делегирую его этому UIViewController.

Заголовок:

#import <UIKit/UIKit.h> 

@interface ResultsExtraVC : UIViewController <UITableViewDelegate, UITableViewDataSource> 
@property(nonatomic, strong) AGTCoreDataStack *model; 
@property (strong, nonatomic) IBOutlet UILabel *labelRaceTime; 
@property (strong, nonatomic) IBOutlet UILabel *labelTrackCondition; 
@property (strong, nonatomic) IBOutlet UILabel *labelRaceStarttime; 
@property (strong, nonatomic) IBOutlet UILabel *labelRaceMode; 
@property (strong, nonatomic) IBOutlet UIScrollView *scrollView; 
@property (weak, nonatomic) IBOutlet UITableView *tableView; 
@property (strong, nonatomic) IBOutlet UIView *raceInfoView; 
@property(nonatomic, strong)NSNumber *eventID; 
@property(nonatomic, strong)NSNumber *sectionID; 
@property(nonatomic, strong)NSNumber *elementID; 
@property(nonatomic, strong)NSNumber *categoryID; 
@end 

Реализация:

#import "ResultsExtraVC.h" 
#import "ResultsExtraCellVC.h" 
#import "Result.h" 
#import "Element.h" 
#import "Section.h" 
#import <CoreData/CoreData.h> 

@interface ResultsExtraVC() <NSFetchedResultsControllerDelegate> 
//Core data 
@property (nonatomic,strong) NSManagedObjectContext* managedObjectContext; 
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController; 
@end 
static NSString * const cellIdentifier = @"resultsExrtaAltCell"; 


@implementation ResultsExtraVC 
@synthesize managedObjectContext; 
@synthesize fetchedResultsController = _fetchedResultsController; 
@synthesize eventID, sectionID, elementID, categoryID, model; 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    managedObjectContext = self.model.context; 

    [self getResults]; 

    NSLog(@"ElementName: %@", [self getElementName]); 
    NSLog(@"SectionName: %@", [self getSectionName]); 
    [self configureHeatInfo]; 
    // Do any additional setup after loading the view. 
} 
- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 

    self.fetchedResultsController = nil; 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 
#pragma mark - View Configuration 
-(void) configureHeatInfo{ 
    _scrollView.backgroundColor = [UIColor cyanColor]; 
    _scrollView.translatesAutoresizingMaskIntoConstraints = NO; 

    _labelRaceTime.translatesAutoresizingMaskIntoConstraints = NO; 
    _labelRaceTime.text = @"Race time:\n10:00"; 

    _labelRaceMode.translatesAutoresizingMaskIntoConstraints = NO; 
    _labelRaceMode.text = @"Mode: Groupstart"; 

    _labelTrackCondition.translatesAutoresizingMaskIntoConstraints = NO; 
    _labelTrackCondition.text = @"Track Condition: Dry"; 

    _labelRaceStarttime.translatesAutoresizingMaskIntoConstraints = NO; 
    _labelRaceStarttime.text = @"Starttime: 12.03.2016 11:09:10"; 

    //self.tableView.translatesAutoresizingMaskIntoConstraints = NO; 
    /*self.tableView.dataSource = self; 
     self.tableView.delegate = self;*/ 
} 

#pragma mark - Table view data source 

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

/*- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return 20; 
}*/ 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    id sectionInfo = [[_fetchedResultsController sections] objectAtIndex:section]; 
    #ifndef NDEBUG 
     NSLog(@"%s (line:%d) - Rows: %lu",__PRETTY_FUNCTION__,__LINE__, (unsigned long)[sectionInfo numberOfObjects]); 
    #endif 
    // Return the number of rows in the section. 

    return [sectionInfo numberOfObjects]; 
} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    return [self basicCellAtIndexPath:indexPath]; 
} 
- (ResultsExtraCellVC *)basicCellAtIndexPath:(NSIndexPath *)indexPath { 
    ResultsExtraCellVC *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

    // Using a cell identifier will allow your app to reuse cells as they come and go from the screen. 
    if (cell == nil) { 
     #ifndef NDEBUG 
      NSLog(@"%s (line:%d)",__PRETTY_FUNCTION__,__LINE__); 
     #endif 
     NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ResultsExtraCell" owner:self options:nil]; 
     cell = (ResultsExtraCellVC *)[nib objectAtIndex:0]; 
    } 
    [self configureCell:cell atIndexPath:indexPath]; 

    return cell; 
} 

- (void)configureCell:(ResultsExtraCellVC *)cell atIndexPath:(NSIndexPath *)indexPath { 
    #ifndef NDEBUG 
     NSLog(@"%s (line:%d)",__PRETTY_FUNCTION__,__LINE__); 
    #endif 

    Result *result = [_fetchedResultsController objectAtIndexPath:indexPath]; 

    [cell.cellRankNr setText:[NSString stringWithFormat:@"%@",[result endposition]]]; 
    [cell.cellName setText:[NSString stringWithFormat:@"%@ %@ (%@)",[result pilotprename], [result pilotname], [result carnumber]]]; 
    [cell.cellResult setText:[NSString stringWithFormat:@"%@",NSLocalizedFormatString(@"LapsXnTimeX",[result rlaps],[result rendtime])]]; 
    [cell.cellRace setText:[NSString stringWithFormat:@"%@",NSLocalizedFormatString(@"BestTimeXnAvgTimeX",[result rbesttime], [result rmediumtime])]]; 

} 

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) 
    { 
     [tableView setSeparatorInset:UIEdgeInsetsZero]; 
    } 

    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) 
    { 
     [tableView setLayoutMargins:UIEdgeInsetsZero]; 
    } 

    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) 
    { 
     [cell setLayoutMargins:UIEdgeInsetsZero]; 
    } 
} 



-(NSString *)getElementName{ 
    NSString *elementName = @""; 

    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Elements" inManagedObjectContext:managedObjectContext]; 
    NSFetchRequest *request = [[NSFetchRequest alloc] init] ; 
    [request setEntity:entityDescription]; 

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(eventid = %@ AND sectionid = %@ AND elementid = %@ AND categoryid= %@)",eventID, sectionID, elementID, categoryID]; 
    [request setPredicate:predicate]; //added this line later 
    NSArray *array = [managedObjectContext executeFetchRequest:request error:nil]; 
    if([array count]> 0){ 
     Element *element = [array lastObject]; 
     elementName = [element name]; 
    } 
    return elementName; 
} 

-(NSString *)getSectionName{ 
    NSString *sectiontName = @""; 

    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Sections" inManagedObjectContext:managedObjectContext]; 


    NSFetchRequest *request = [[NSFetchRequest alloc] init] ; 
    [request setEntity:entityDescription]; 

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(eventid = %@ AND sectionid = %@)",eventID, sectionID]; 
    [request setPredicate:predicate]; //added this line later 
    NSArray *array = [managedObjectContext executeFetchRequest:request error:nil]; 
    if([array count]> 0){ 
     Section *section = [array lastObject]; 
     sectiontName = [section name]; 
    } 
    return sectiontName; 
} 

-(void)getResults{ 
    // Initialize Fetch Request 
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Results"]; 

    // Add Sort Descriptors 
    //[fetchRequest setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"endposition" ascending:YES]]]; 

    //Predicate 
    NSPredicate *commentsPredicate = [NSPredicate predicateWithFormat:@"(eventid = %@ AND sectionid = %@ AND elementid = %@)",eventID, sectionID, elementID]; 
    [fetchRequest setPredicate:commentsPredicate]; //added this line later 

    // Edit the sort key as appropriate. 
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"endposition" 
                    ascending:YES]; 
    NSArray *sortDescriptors = @[sortDescriptor]; 

    [fetchRequest setSortDescriptors:sortDescriptors]; 

    // Initialize Fetched Results Controller 
    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil]; 

    // Configure Fetched Results Controller 
    [self.fetchedResultsController setDelegate:self]; 

    // Perform Fetch 
    NSError *error = nil; 
    [self.fetchedResultsController performFetch:&error]; 

    if (error) { 
     NSLog(@"Unable to perform fetch."); 
     NSLog(@"%@, %@", error, error.localizedDescription); 
    } 
} 
#pragma mark - 
#pragma mark Fetched Results Controller Delegate Methods 
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { 
    [self.tableView beginUpdates]; 
} 

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

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { 
    switch (type) { 
     case NSFetchedResultsChangeInsert: { 
      [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
     } 
     case NSFetchedResultsChangeDelete: { 
      [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
     } 
     case NSFetchedResultsChangeUpdate: { 
      [self configureCell:(ResultsExtraCellVC *)[self.tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; 
      break; 
     } 
     case NSFetchedResultsChangeMove: { 
      [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
     } 
    } 
} 
@end 

Мой Вид выглядит следующим образом: enter image description here

Я пытался следовать некоторым учебникам, как это первый раз, когда я делаю это с CoreData, ранее я всегда использовал только UITableViewController. я следовал за этим: http://code.tutsplus.com/tutorials/core-data-from-scratch-more-nsfetchedresultscontroller--cms-21777 А также проверил: CoreData TableView inside UIViewController

Но без успеха. Мне было бы здорово, если кто-то может помочь мне с проблемой.

Заранее спасибо

+0

Какие значения вы фактически возвращаете из 'numberOfSectionsInTableView' и' numberOfRowsInSection'? –

+0

Привет, Phillip, он возвращает 0, вот почему не показывает строки, проблема в том, что объект Results имеет контент и другие запросы в viewDidLoad: NSLog (@ "ElementName:% @", [self getElementName]) ; NSLog (@ "SectionName:% @", [self getSectionName]); возвращает контент, поэтому модель и контекст установлены в порядке. – Miguel

ответ

0

Может быть, в строке кода

// Initialize Fetched Results Controller 
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil]; 

sectionNameKeyPath отсутствует? Он должен быть одним из ключей NSSortDescriptor.