My setup:
I have a UIViewController with a TableView inserted in it. Also in the viewController I have a textfield and a slider. I am trying to persist data from my text field, store it and then have fetch request populate the cells with whatever information was placed in the textField. However, when I hit the save button nothing populates the tableCell. The .m file below is of my UIVeiwController. Any help would be great as to why the cell isn't populating. Thanks!
#import "BottleViewController.h"
#import "LogEntry.h"
#import "CoreDataStack.h"
#interface BottleViewController () <NSFetchedResultsControllerDelegate>
#property (strong, nonatomic) IBOutlet UILabel *ouncesLabel;
#property (strong, nonatomic) UISlider *slider;
#property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#property (strong, nonatomic) IBOutlet UILabel *entryAmount;
#property (strong, nonatomic) IBOutlet UITextField *textField;
#end
#implementation BottleViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self.fetchedResultsController performFetch:nil];
}
-(void)dismissSelf{
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}
-(void)insertLogEntry {
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
LogEntry *entry = [NSEntityDescription insertNewObjectForEntityForName:#"LogEntry" inManagedObjectContext:coreDataStack.managedObjectContext];
entry.amount = self.slider.value;
entry.date = [[NSDate date] timeIntervalSince1970];
entry.testString = self.textField.text;
[coreDataStack saveContext];
}
- (IBAction)backWasPressed:(id)sender {
[self dismissSelf];
}
- (IBAction)mySlider:(id)sender {
self.slider = (UISlider*)sender;
NSString *newText = [[NSString alloc] initWithFormat:#"%d", (int)self.slider.value];
self.ouncesLabel.text = newText;
}
- (IBAction)saveWasPressed:(id)sender {
[self.view endEditing:YES];
[self insertLogEntry];
}
-(NSFetchRequest *)entryListFetchRequest{
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"LogEntry"];
fetchRequest.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"date" ascending:NO]];
return fetchRequest;
}
-(NSFetchedResultsController *)fetchedResultsController{
if(_fetchedResultsController != nil){
return _fetchedResultsController;
}
CoreDataStack *coreDataStack =[CoreDataStack defaultStack];
NSFetchRequest *fetchRequest = [self entryListFetchRequest];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:coreDataStack.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
#pragma mark UITableViewDelegates
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return self.fetchedResultsController.sections.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
id<NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController sections][section];
return [sectionInfo numberOfObjects];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier =#"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
LogEntry *entry = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = entry.testString;
return cell;
}
-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
[self.tableView reloadData];
}
#end
Nevermind figured it out. I forgot to connect the datasource and delegates.
Related
I am trying to create a setting page for an app that uses Table View Controllers to pass data back changing the detailed text label of the first view controller depending on the text of the selected row of the second Table View Controller. I put a NSLog in under my delegate method on the initial Table View Controller and it is not being called. I am very stuck, any help is greatly appreciated!
Initial VC .h:
// EditAlarmTVC.h (Initial table view controller .h file)
//
#import <UIKit/UIKit.h>
#import "AlarmSoundTVC.h"
#interface EditAlarmTVC : UITableViewController <AlarmSoundDelegate>
#property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;
#property (weak, nonatomic) IBOutlet UITableViewCell *offMethodCell;
#property (weak, nonatomic) IBOutlet UITableViewCell *repeateCell;
#property (weak, nonatomic) IBOutlet UITableViewCell *alarmLabelCell;
#property (weak, nonatomic) IBOutlet UITableViewCell *alarmSoundCell;
#property (strong) NSManagedObjectModel *alarm;
- (IBAction)cancelSetAlarm:(id)sender;
- (IBAction)saveSetAlarm:(id)sender;
#end
Initial VC .m:
//EditAlarmTVC.m (Initial table view controller.m file)
#import "EditAlarmTVC.h"
#import <CoreData/CoreData.h>
#interface EditAlarmTVC ()
#property (weak, nonatomic) IBOutlet UITableView *myTableView;
#property (retain, nonatomic) NSMutableArray *detailedTextLabels;
#end
#implementation EditAlarmTVC
#synthesize alarm;
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"offMethod"];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"timePicker"];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"repeateLabelSoundCell"];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"deleteAlarmCell"];
self.detailedTextLabels =[NSMutableArray array];
[self.detailedTextLabels addObject:#"Off"];
[self.detailedTextLabels addObject:#"Never"];
[self.detailedTextLabels addObject:#"Wake up, get up!"];
[self.detailedTextLabels addObject:#"Default"];
}
-(void) viewWillAppear:(BOOL)animated{
[self.offMethodCell.detailTextLabel setText:[self.detailedTextLabels objectAtIndex:0]];
[self.repeateCell.detailTextLabel setText:[self.detailedTextLabels objectAtIndex:1]];
[self.alarmLabelCell.detailTextLabel setText:[self.detailedTextLabels objectAtIndex:2]];
[self.alarmSoundCell.detailTextLabel setText:[self.detailedTextLabels objectAtIndex:3]];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)sendSelection:(NSString *)selectedAlarm{
NSLog(#"hello");
[self.detailedTextLabels replaceObjectAtIndex:3 withObject:selectedAlarm];
[self.myTableView reloadData];
}
-(NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context =nil;
id delegat = [[UIApplication sharedApplication] delegate];
if ([delegat respondsToSelector:#selector(managedObjectContext)]) {
context = [delegat managedObjectContext];
}
return context;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section ==2 & indexPath.row==0){
[self performSegueWithIdentifier:#"repeateSegue" sender:indexPath];
} else if (indexPath.section ==2 & indexPath.row==1){
[self performSegueWithIdentifier:#"alarmLabelSegue" sender:indexPath];
} else if (indexPath.section ==0 & indexPath.row==0){
[self performSegueWithIdentifier:#"offMethodSegue" sender:indexPath];
} else if (indexPath.section ==2 & indexPath.row==2){
[self performSegueWithIdentifier:#"alarmSoundSegue" sender:indexPath];
} else if (indexPath.section ==3 & indexPath.row==0){
//DELETE ALARM
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Alarm" inManagedObjectContext:context];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc]init];
[timeFormatter setDateFormat:#"h:mm"];
NSDate *timeNSDate = [self.datePicker date];
NSString *timeString = [timeFormatter stringFromDate:timeNSDate];
NSDateFormatter *amPmFormatter = [[NSDateFormatter alloc]init];
[amPmFormatter setDateFormat:#"a"];
NSDate *amPmNSDate = [self.datePicker date];
NSString *amPmString = [amPmFormatter stringFromDate:amPmNSDate];
NSPredicate *p1 = [NSPredicate predicateWithFormat:#"time == %#", timeString];
NSPredicate *p2 = [NSPredicate predicateWithFormat:#"amPm == %#", amPmString];
NSPredicate *p3 = [NSPredicate predicateWithFormat:#"offMethod == %#", self.offMethodCell.detailTextLabel.text];
NSPredicate *p4 = [NSPredicate predicateWithFormat:#"repeate == %#", self.repeateCell.detailTextLabel.text];
NSPredicate *p5 = [NSPredicate predicateWithFormat:#"alarmSound == %#", self.alarmSoundCell.detailTextLabel.text];
NSPredicate *p6 = [NSPredicate predicateWithFormat:#"alarmLabel == %#", self.alarmLabelCell.detailTextLabel.text];
NSPredicate *alarmsPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:#[p1, p2, p3, p4, p5, p6]];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:alarmsPredicate];
NSError *error;
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *managedObject in items)
{
[context deleteObject:managedObject];
}
EditAlarmTVC *goToEditAlarmTVC = [self.storyboard instantiateViewControllerWithIdentifier:#"setAlarmVC"];
[self.navigationController pushViewController:goToEditAlarmTVC animated:YES];
[self dismissViewControllerAnimated:NO completion:nil];
} else
return;
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"alarmSoundSegue"])
{
AlarmSoundTVC *alarmSoundTVC = [[AlarmSoundTVC alloc]init];
[alarmSoundTVC setDelegate:self];
}
}
#end
Second VC .h:
//AlarmSoundTVC.h (Second table view controller .h file)
#import <UIKit/UIKit.h>
#protocol AlarmSoundDelegate <NSObject>
#required
-(void) sendSelection:(NSString *)selectedAlarm;
#end
#interface AlarmSoundTVC : UITableViewController
#property (strong, nonatomic) IBOutlet UITableView *myTableView;
#property (nonatomic, weak) id <AlarmSoundDelegate> delegate;
#end
Second VC .m:
// AlarmSoundTVC.m (Second table view controller .m file)
#import "AlarmSoundTVC.h"
#import "EditAlarmTVC.h"
#interface AlarmSoundTVC ()
#end
#implementation AlarmSoundTVC
- (void)viewDidLoad {
[super viewDidLoad];
self.myTableView.delegate = self;
}
-(void) viewWillDisappear:(BOOL)animated{
NSIndexPath *indexPath = [self.myTableView indexPathForSelectedRow];
UITableViewCell *selectedCell =[self.myTableView cellForRowAtIndexPath:(indexPath)];
NSString *selectedAlarm = selectedCell.textLabel.text;
[self.delegate sendSelection:selectedAlarm] ;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
//- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// }
#end
I am sorry if there is some extra unnecessary code in there. I am a bit new and wanted to be sure I provided plenty of information. Thanks again!
In your prepareForSegue you are setting the delegate on a new, local, instance of AlarmSoundTVC, that will be discarded as soon as the method exits. You need to use the instance that is going to be presented, which can be accessed via the destinationViewController property of the segue:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"alarmSoundSegue"])
{
AlarmSoundTVC *alarmSoundTVC = (AlarmSoundTVC *)segue.destinationViewController;
[alarmSoundTVC setDelegate:self];
}
}
I'm getting correct data after loading the page as shown in this screen
getting correct data even after performing search like this image
but after search is cancelled im getting wrong data (label should be ph:+ and Fax:+ but its displaying both as Fax:+ like this
with this code
#implementation Staffdir
#synthesize tableview,filteredContentList,searchBar1;
- (void)viewDidLoad {
searchBar1.delegate = self;
__block StaffDirectoryModel*staffdirectorymodel;
NSURL *url = [NSURL URLWithString:#"http://dev.devobal.com/GetData.aspx?Query=select%20*%20from%20tb_RHP_Staff_Directory"];
_staffdirarr=[[NSMutableArray alloc]init];
NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:url];
[[[NSURLSession sharedSession]dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSMutableArray *jsonarr=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
dispatch_sync(dispatch_get_main_queue(), ^{
// Update UI
for(int i=0;i<jsonarr.count;i++){
staffdirectorymodel=[[StaffDirectoryModel alloc]init];
staffdirectorymodel.name =[[jsonarr objectAtIndex:i]objectForKey:#"Name"];
staffdirectorymodel.occupation=[[jsonarr objectAtIndex:i]objectForKey:#"Job_Title"];
staffdirectorymodel.phonelabel =[[jsonarr objectAtIndex:i]objectForKey:#"Phone"];
staffdirectorymodel.faxlabel =[[jsonarr objectAtIndex:i]objectForKey:#"Fax_Number"];
staffdirectorymodel.department =[[jsonarr objectAtIndex:i]objectForKey:#"Department"];
[_staffdirarr addObject:staffdirectorymodel];
staffdirectorymodel=nil;
}
[tableview reloadData];
});
}]resume];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
//-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
// return 1;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (isSearching) {
return [searchResults count];
}else{
return _staffdirarr.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellidentifer = #"cell";
StaffDirectoryModel*staffdirectorymodel=[[StaffDirectoryModel alloc]init];
Staffcustom *cell= [tableView dequeueReusableCellWithIdentifier:cellidentifer];
if (cell == nil) {
cell = [[Staffcustom alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentifer];
}
[cell.fxlabel setHidden:NO];
[cell.faxnumlabel setHidden:NO];
if (isSearching) {
staffdirectorymodel=[searchResults objectAtIndex:indexPath.row];
cell.namelabel.text = staffdirectorymodel.name;
cell.occupationlabel.text = staffdirectorymodel.occupation;
NSString*tempph=staffdirectorymodel.phonelabel;
NSString*tempfax=staffdirectorymodel.faxlabel;
if(tempph.length!=0)
{
cell.phonelabel.text = staffdirectorymodel.phonelabel;
}
else{
cell.phlabel.text=#"Fax: +";
cell.phonelabel.text = staffdirectorymodel.faxlabel;
[cell.fxlabel setHidden:YES];
[cell.faxnumlabel setHidden:YES];
}
if(tempfax.length==0)
{
[cell.faxnumlabel setHidden:YES];
[cell.fxlabel setHidden:YES];
}
if([tempph length]!=0 &&[tempfax length]!=0){
cell.faxnumlabel.text = staffdirectorymodel.faxlabel;
}
cell.Depart.text = staffdirectorymodel.department;
}
else{
staffdirectorymodel=[_staffdirarr objectAtIndex:indexPath.row];
cell.namelabel.text = staffdirectorymodel.name;
cell.occupationlabel.text = staffdirectorymodel.occupation;
NSString*tempph=staffdirectorymodel.phonelabel;
NSString*tempfax=staffdirectorymodel.faxlabel;
if(tempph.length!=0)
{
cell.phonelabel.text = staffdirectorymodel.phonelabel;
}
else{
cell.phlabel.text=#"Fax: +";
cell.phonelabel.text = staffdirectorymodel.faxlabel;
[cell.fxlabel setHidden:YES];
[cell.faxnumlabel setHidden:YES];
}
if(tempfax.length==0)
{
[cell.faxnumlabel setHidden:YES];
[cell.fxlabel setHidden:YES];
}
if([tempph length]!=0 &&[tempfax length]!=0){
cell.faxnumlabel.text = staffdirectorymodel.faxlabel;
}
cell.Depart.text = staffdirectorymodel.department;
}
cell.namelabel.textColor = [UIColor blueColor];
cell.occupationlabel.textColor=[UIColor colorWithRed:0.5 green:0.0 blue:1 alpha:1.0];
UIView * additionalSeparator = [[UIView alloc] initWithFrame:CGRectMake(0,cell.frame.size.height-1,cell.frame.size.width,0.1)];
additionalSeparator.backgroundColor = [UIColor blueColor];
[cell addSubview:additionalSeparator];
return cell;
}
//- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
// isSearching = YES;
//}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)searchText
{
//[filteredContentList removeAllObjects];
if(searchText.length!=0){
isSearching=YES;
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"name contains[c] %#",
searchText];
searchResults=(NSMutableArray *)[_staffdirarr filteredArrayUsingPredicate:resultPredicate];
[tableview reloadData];
}
else{
isSearching=NO;
[tableview reloadData];
}
//
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
isSearching=YES;
[tableview reloadData];}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
isSearching=NO;
[tableview reloadData];}
and
staffdirectory model class
#interface StaffDirectoryModel : NSObject
#property (nonatomic,retain) NSString*name;
#property (nonatomic,retain) NSString*occupation;
#property (nonatomic,retain) NSString*phlabel;
#property (nonatomic,retain) NSString*phonelabel;
#property (nonatomic,retain) NSString*fxlabel;
#property (nonatomic,retain) NSString*faxlabel;
#property (nonatomic,retain) NSString*department;
staffcustom.h
#interface Staffcustom : UITableViewCell
#property (strong, nonatomic) IBOutlet UILabel *fxlabel;
#property (weak, nonatomic) IBOutlet UILabel *namelabel;
#property (weak, nonatomic) IBOutlet UILabel *occupationlabel;
#property (weak, nonatomic) IBOutlet UILabel *phlabel;
#property (weak, nonatomic) IBOutlet UILabel *faxlabel;
#property (weak, nonatomic) IBOutlet UILabel *phonelabel;
#property (weak, nonatomic) IBOutlet UILabel *faxnumlabel;
#property (nonatomic,retain) IBOutlet UILabel *Depart;
#end
I would like to explain the most detailed the problem I'm facing.
Previously instead of the UIViewController i had directly a UITableViewController, the problem is that now i need to show more content in the view that just the tableview so i created a new view. Now i have a UIViewController that has: UIScrollView. Enside of it there are: 1. UIView + 1 UITableView
I'm using AutoLayout. And is working fine. The problem I'm facing is that since i switched to use this view I'm unable to display content in the table with coredata. I was able to do it without coredata but not with it.
In the interfacebuilder i set datasource and delegate to this UIViewController.
Header:
#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
Implementation:
#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
My View looks like this:
I tried to follow some tutorials as this is the first time i'm doing this with CoreData, previously i always used only UITableViewController.
I followed this: http://code.tutsplus.com/tutorials/core-data-from-scratch-more-nsfetchedresultscontroller--cms-21777
And also checked: CoreData TableView inside UIViewController
But with no success.
I would be great if someone can help me with the problem.
Thanks in advance
Maybe in code line
// Initialize Fetched Results Controller
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
the sectionNameKeyPath is missing? It must be one of the NSSortDescriptor keys.
In my app i want to store data in core data and that data should be display on cell of UITableView.
Now I had successfully store the data in core data.
Now how to display all my data on cell of UITableView?
Now I had edited some TasksViewController.m code
TasksViewController.h
#interface TasksViewController : UIViewController
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (strong) NSMutableArray *tasks;
#property (nonatomic,retain) NSMutableArray *taskTaskNameArray,*taskColorTagArray,*taskProjectName,*taskStartingTimeArray,*taskCompletingTimeArray;
#property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
#property (nonatomic, strong) NSManagedObjectContext *context;
#property (nonatomic,retain) NSFetchRequest *fetchRequest;
#end
TasksViewController.m
#implementation TasksViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Task"];
fetchRequest.resultType = NSDictionaryResultType;
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:#"task_name",#"color_tag",#"project_name",#"completing_date",#"starting_date",nil]];
NSError *error = nil;
_arrayTasks = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
_taskTaskNameArray = [self.arrayTasks valueForKey:#"task_name"];
_taskColorTagArray = [self.arrayTasks valueForKey:#"color_tag"];
_taskProjectNameArray = [self.arrayTasks valueForKey:#"project_name"];
_taskStartingTimeArray = [self.arrayTasks valueForKey:#"starting_date"];
_taskCompletingTimeArray = [self.arrayTasks valueForKey:#"completing_date"];
[self.tableView reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _arrayTasks.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
TasksTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[TasksTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.lblTaskName.text = [_arrayTask objectAtIndex:indexPath.row ];
cell.lblColorTag.text = [_arrayTask objectAtIndex:indexPath.row];
cell.lblProjectName.text = [_arrayTask objectAtIndex:indexPath.row];
cell.lblCompletingDate.text = [_arrayTask objectAtIndex:indexPath.row];
cell.lblStartingDate.text = [_arrayTask objectAtIndex:indexPath.row];
return cell;
}
#end
Tasks.h
#interface Tasks : NSManagedObject
#property (nonatomic,retain) NSString *taskTaskName,*taskColorTag,*taskProjectName,*taskStartingDate,*taskCompletingDate;
#end
Task.m
#implementation Tasks
#dynamic taskTaskName;
#dynamic taskColorTag;
#dynamic taskProjectName;
#dynamic taskStartingDate;
#dynamic taskCompletingDate;
#end
TasksTableViewCell.h
#interface TasksTableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *lblTaskName;
#property (weak, nonatomic) IBOutlet UILabel *lblColorTag;
#property (weak, nonatomic) IBOutlet UILabel *lblProjectName;
#property (weak, nonatomic) IBOutlet UILabel *lblStartingTime;
#property (weak, nonatomic) IBOutlet UILabel *lblCompletingTime;
#end
TasksTableViewCell.m
#implementation TasksTableViewCell
- (void)awakeFromNib {
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
I had tried this code but it is not working and not display data on cell of UITableView.
I had edited some code in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath of TasksTableViewController.m .
I had store data of core in array and whole Task table is store in arrayTask and its attribute are also stores in different different array like taskname in _taskTaskNameArray and like that...
Thanks for any help.
Try this:
1. update NSSortDescriptor like this:
NSSortDescriptor *taskNameDescriptor = [[NSSortDescriptor alloc]initWithKey:#"taskTaskName" ascending:YES];
NSSortDescriptor *subTaskDescriptor = [[NSSortDescriptor alloc]initWithKey:#"taskColorTag" ascending:YES];
NSSortDescriptor *startingDateDescriptor = [[NSSortDescriptor alloc]initWithKey:#"taskStartingDate" ascending:YES];
NSSortDescriptor *completingDateDescriptor = [[NSSortDescriptor alloc]initWithKey:#"taskCompletingDate" ascending:YES];
NSSortDescriptor *projectNameDescriptor = [[NSSortDescriptor alloc]initWithKey:#"taskProjectName" ascending:YES];
// ...
Sort key should be same with property name.
use dequeueReusableCellWithIdentifier:forIndexPath: instead of dequeueReusableCellWithIdentifier: to make sure the cell isn't nil.
Change array to self.tasks and index to indexpath.row
- (void)configureCell:(TasksTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
// Configure the cell to show the book's title
Tasks *tasks = [self.tasks objectAtIndexPath:indexPath.row];
// YOUR CODE
}
Thanks.
I have project with normal cell and working success but I want to change it with custom cell I added Cell.h and Cell.m files into my project and I need to integrate custom cell to my working cell. And last I want to show detail view title description and image (I added title codes working) My codes under
Cell.h
#import <UIKit/UIKit.h>
#interface Cell : UITableViewCell
#property (nonatomic, weak) IBOutlet UIImageView *imaj;
#property (nonatomic, weak) IBOutlet UILabel *descriptionLabel;
#property (nonatomic, weak) IBOutlet UILabel *titleLabel;
#end
Cell.m
#import "Cell.h"
#implementation Cell
#synthesize imaj = _imaj;
#synthesize descriptionLabel = _descriptionLabel;
#synthesize titleLabel = _titleLabel;
#end
ViewController.m
#import "MasterViewController.h"
#import "DetailViewController.h"
#import "SDWebImage/UIImageView+WebCache.h"
#import "MBProgressHUD.h"
#import "Cell.h"
static NSString *const kConsumerKey = #"a1SNULSPtp4eLQTsTXKKSgXkYB5H4CMFXmleFvqE";
#interface MasterViewController () <UISearchBarDelegate, UISearchDisplayDelegate,MBProgressHUDDelegate>{
MBProgressHUD *HUD;
}
#property (nonatomic, assign) NSInteger currentPage;
#property (nonatomic, assign) NSInteger totalPages;
#property (nonatomic, assign) NSInteger totalItems;
#property (nonatomic, assign) NSInteger maxPages;
#property (nonatomic, strong) NSMutableArray *activePhotos;
#property (strong, nonatomic) NSMutableArray *staticDataSource;
#property (nonatomic, strong) NSMutableArray *searchResults;
#property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#end
#implementation MasterViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.activePhotos = [[NSMutableArray alloc] init];
self.searchResults = [[NSMutableArray alloc] init];
self.staticDataSource = [[NSMutableArray alloc] init];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self loadPhotos:self.currentPage];
}
#pragma mark - Table View
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// if (self.currentPage == self.maxPages
// || self.currentPage == self.totalPages
// || self.currentPage == self.totalPages
// || self.totalItems == self.photos.count) {
// return self.photos.count;
// } else if (self.tableView == self.searchDisplayController.searchResultsTableView){
// return [self.searchResults count];
//
// }
// return self.photos.count + 1;
return self.activePhotos.count + 1;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (self.currentPage != self.maxPages && indexPath.row == [self.staticDataSource count] - 1 ) {
[self loadPhotos:++self.currentPage];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
if (indexPath.row == [self.activePhotos count]) {
cell = [self.tableView dequeueReusableCellWithIdentifier:#"LoadingCell" forIndexPath:indexPath];
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
HUD.delegate = self;
HUD.labelText = #"Loading";
[HUD showWhileExecuting:#selector(myTask) onTarget:self withObject:nil animated:YES];
} else {
NSDictionary *photoItem = self.activePhotos[indexPath.row];
cell = [self.tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
// cell.textLabel.text = [self.searchResults[indexPath.row] valueForKey:#"name"];
// } else {
// NSDictionary *photoItem = self.photos[indexPath.row];
cell.textLabel.text = [photoItem objectForKey:#"name"];
if (![[photoItem objectForKey:#"description"] isEqual:[NSNull null]]) {
cell.detailTextLabel.text = [photoItem objectForKey:#"description"];
}
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:[photoItem objectForKey:#"image_url"] ] placeholderImage:[UIImage imageNamed:#"placeholder.jpg"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (error) {
NSLog(#"Error occured : %#", [error description]);
}
}];
}
// NSLog(#"%#",self.searchResults);
return cell;
}
- (void)myTask {
// Do something usefull in here instead of sleeping ...
sleep(1.5);
}
#pragma mark UISearchDisplay delegate
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
// [self.searchResults removeAllObjects];
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF.name contains[c] %#", searchText];
self.activePhotos = [NSMutableArray arrayWithArray:[self.staticDataSource filteredArrayUsingPredicate:resultPredicate]];
//[self.tableData filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
- (void)loadPhotos:(NSInteger)page
{
NSString *apiURL = [NSString stringWithFormat:#"https://api.500px.com/v1/photos?feature=editors&page=%ld&consumer_key=%#",(long)page,kConsumerKey];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:apiURL]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
if (!error) {
NSError *jsonError = nil;
NSMutableDictionary *jsonObject = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
NSLog(#"%#",jsonObject);
[self.staticDataSource addObjectsFromArray:[jsonObject objectForKey:#"photos"]];
self.currentPage = [[jsonObject objectForKey:#"current_page"] integerValue];
self.totalPages = [[jsonObject objectForKey:#"total_pages"] integerValue];
self.totalItems = [[jsonObject objectForKey:#"total_items"] integerValue];
self.activePhotos = self.staticDataSource;
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
}] resume];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
DetailViewController *vc = segue.destinationViewController;
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
vc.StoreList = [self.activePhotos objectAtIndex:indexPath.row];
}
#end
Also I uploaded working project here
http://www.filedropper.com/needcustomcell
In your
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Cell *cell;
// rest of your code
}
that would do it. You have used UITableViewCell you need to replace ot with your custom cell class.