how to display core data on cell in ios? - ios

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.

Related

Delegate not being called when passing back data between Table View Controllers

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

Error initializing object. Can't set value to PFObject

I can't figure out why I am unable to set the value of an instance of PFObject. It is working successfully elsewhere in the app, but I must be doing something wrong in this view. I'd really appreciate your help figuring out what I'm missing. Thanks.
Basically
self.ABC.type = #"Frustrated";
NSLog(#"why is this null? -----> %#",self.ABC.type);
2015-10-18 18:26:29.277 XX [885:109003] why is this null? -----> (null)
Why is the value not being assigned? It should log as ... I'm not null or frustrating... I'm working, see -----> Frustrated !!!!!! but it is not working!
I'm therefore unable to set the object in Parse bc it's nil and the app crashes.
Below should be all and more of the code you need, but let me know it you have questions or suggestions. Thanks!:
FCollectionViewController.m:
#import "FCollectionViewController.h"
#import "FCell.h"
#import "SectionHeaderView.h"
#import "MBProgressHUD.h"
#import "Helper.h"
#interface FCollectionViewController()
<UICollectionViewDelegate, MBProgressHUDDelegate>
#property (nonatomic, strong) NSDictionary *presetsDictionary;
#property (nonatomic, strong) NSArray *presets;
#property (nonatomic, strong) NSIndexPath *textViewIndexPath;
#property (nonatomic, strong) FCell *fCell;
#property (nonatomic, strong) MBProgressHUD *HUD;
#property (nonatomic, strong) NSArray *headTitleArray;
#end
#implementation FCollectionViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.headTitleArray = [NSArray arrayWithObjects:
#"type",
#"model",
#"feature", nil];
PFQuery *query = [PFQuery queryWithClassName:#"Presets"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
NSMutableArray *keys = [[NSMutableArray alloc] init];
NSMutableArray *values = [[NSMutableArray alloc] init];
for (PFObject *obj in objects) {
[keys addObject:[obj objectForKey:#"key"]];
[values addObject:[obj objectForKey:#"value"]];
}
self.presetsDictionary = [NSDictionary dictionaryWithObjects:values forKeys:keys];
self.presets = [[NSMutableArray alloc] initWithObjects:
[self.presetsDictionary objectForKey:#"type"],
[self.presetsDictionary objectForKey:#"model"],
[self.presetsDictionary objectForKey:#"feature"],nil];
NSLog(#"self.presets ----> %#", self.presets);
[self.collectionView reloadData];
}];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return [self.presets count];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [self.presets[section] count];
}
- (UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView * view = nil;
if ([kind isEqualToString:UICollectionElementKindSectionHeader])
{
ItemSectionHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([ItemSectionHeaderView class])
forIndexPath:indexPath];
header.captionLabel.text = self.headTitleArray[indexPath.section];
view = header;
}
return view;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell;
FCell *aCell = (FCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"fCell" forIndexPath:indexPath];
aCell.label.text = self.presets[indexPath.section][indexPath.row];
aCell.label.textAlignment = NSTextAlignmentCenter;
cell = aCell;
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize size;
....
return size;
}
#pragma mark <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSArray * selectedRows = self.collectionView.indexPathsForSelectedItems;
for (NSIndexPath * selectedRow in selectedRows) {
if ((selectedRow.section == indexPath.section) && (selectedRow.row != indexPath.row)) {
[self.collectionView deselectItemAtIndexPath:selectedRow animated:NO];
}
}
switch (indexPath.section) {
case 0:
self.aBC.type = #"Frustrated";
NSLog(#"why isn't this being assigned? -----> %#",self.ABC.type);
break;
case 1:
self.aBC.model = self.presets[indexPath.section][indexPath.row];
NSLog(#"why is this null?!!!! -----> %#",self.ABC.model);
NSLog(#"this DOES log the value I want!! -----> %#",self.presets[indexPath.section][indexPath.row]);
break;
case 2:
...
default:
break;
}
}
FCollectionViewController.h:
#import <UIKit/UIKit.h>
#import "ABC.h"
#interface FCollectionViewController : UICollectionViewController
//<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
#property (nonatomic, strong) ABC *aBC;
#end
ABC.h:
#import <Foundation/Foundation.h>
#interface ABC : NSObject
#property (nonatomic, strong) NSString *type;
#property (nonatomic, strong) NSString *model;
#property (nonatomic, strong) NSString *feature;
#property (nonatomic, strong) PFObject *pfObj;
#property (nonatomic, strong) PFUser *user;
- (id)initWithPFObject:(PFObject *)anObject;
#end
ABC.m:
#import "ABC.h"
#implementation ABC
- (id)initWithPFObject:(PFObject *)anObject
{
if(self = [super init])
{
[anObject fetchIfNeeded];
self.pfObj = anObject;
self.type = [anObject objectForKey:#"type"];
self.model = [anObject objectForKey:#"model"];
...
}
return self;
}
#end
FCell.h:
#import <UIKit/UIKit.h>
#interface FCell : UICollectionViewCell
#property (weak, nonatomic) IBOutlet UILabel *label;
#end
FCell.m:
#import "FCell.h"
#implementation FCell
-(void)setHighlighted:(BOOL)highlighted
{
[super setHighlighted:highlighted];
self.selectedBackgroundView = [[UIView alloc] initWithFrame:self.frame];
self.selectedBackgroundView.backgroundColor = [UIColor darkGrayColor];
[self setNeedsDisplay];
}
#end
aBC isn't initialized anywhere. You declare it, but it isn't initialized. So setting aBC.type isn't actually setting anything.
Add self.aBC = [[ABC alloc] init]; in your viewDidLoad method.

UITableView programatically added to View Controller won't populate

I've programmatically created a UITableView within my MatchCenterViewController, however it doesn't seem to populate with the JSON data being returned by my cloud code function. It simply shows a blank View Controller. MatchCenterViewController is a ViewController embedded within a Navigation View Controller.
MatchCenterViewController.h:
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "AsyncImageView.h"
#import "SearchViewController.h"
#interface MatchCenterViewController : UIViewController <UITableViewDataSource>
#property (nonatomic) IBOutlet NSString *itemSearch;
#property (nonatomic, strong) NSArray *imageURLs;
#property (strong, nonatomic) NSString *matchingCategoryCondition;
#property (strong, nonatomic) NSString *matchingCategoryLocation;
#property (strong, nonatomic) NSNumber *matchingCategoryMaxPrice;
#property (strong, nonatomic) NSNumber *matchingCategoryMinPrice;
#property (strong, nonatomic) NSArray *matchCenterArray;
#end
MatchCenterViewController.m:
#import "MatchCenterViewController.h"
#import <UIKit/UIKit.h>
#interface MatchCenterViewController () <UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, strong) UITableView *matchCenter;
#end
#implementation MatchCenterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
_matchCenter.dataSource = self;
_matchCenter.delegate = self;
[self.view addSubview:self.matchCenter];
}
return self;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [_matchCenter dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *matchCenterDictionary= [self.matchCenterArray objectAtIndex:indexPath.row];
cell.textLabel.text = [matchCenterDictionary objectForKey:#"Title"];// title of the first object
// if([matchCenterDictionary objectForKey:#"Price"] != NULL)
// {
// cell.detailTextLabel.text = [NSString stringWithFormat:#"$%#",[matchCenterDictionary objectForKey:#"Price"]];
// }
return cell;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.matchCenterArray = [[NSArray alloc] init];
}
- (void)viewDidAppear:(BOOL)animated
{
self.matchCenterArray = [[NSArray alloc] init];
[PFCloud callFunctionInBackground:#"MatchCenterTest"
withParameters:#{
#"test": #"Hi",
}
block:^(NSDictionary *result, NSError *error) {
if (!error) {
self.matchCenterArray = [result objectForKey:#"Top 3"];
dispatch_async(dispatch_get_main_queue(), ^{
[_matchCenter reloadData];
});
NSLog(#"Test Result: '%#'", result);
}
}];
}
#end
How do you create this viewController? If you don't use [[MatchCenterViewController alloc] initWithNibName:... bundle:...] the table creation won't be called. This might happen because you have the viewController in a storyBoard, in this case initWithCoder: would be the method to overwrite.
I would recommend to move this code to viewDidLoad, which will be called regardless how the viewController was created . E.g.:
- (void)viewDidLoad {
[super viewDidLoad];
self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
_matchCenter.dataSource = self;
_matchCenter.delegate = self;
[self.view addSubview:self.matchCenter];
self.matchCenterArray = [[NSArray alloc] init];
}

TableView Cells not displaying info

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.

UITableView not displaying data.

I'm new to iOS and just trying to get data to display in UITableView. I basically have a project set up about authors. I want to display author names etc. So i have an Author model and AuthorsViewController which is a datasource and delegate for UITableView etc. I'm using storyboard (MainStoryboard) tableview and managed to connect it to AuthorsViewController in the "Identity Inspector".
Image of Storyboard if it helps, thanks:
Here, first, is the model: Author.h
#import <Foundation/Foundation.h>
#interface Author : NSObject
#property (nonatomic, strong) NSString *name;
#property (nonatomic, strong) NSString *book;
#property (nonatomic) int year;
#end
Author.m
#import "Author.h"
#implementation Author
#end
Here is the AuthorsViewController.h
#interface AuthorViewController : UITableViewController
<UITableViewDataSource, UITableViewDelegate>
#end
And AuthorsViewController.m
#import "AuthorViewController.h"
#interface AuthorViewController ()
#property (nonatomic, strong) NSMutableArray *authors;
#end
#implementation AuthorViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_authors = [[NSMutableArray alloc] init];
Author *auth = [[Author alloc] init];
[auth setName:#"David Powers"];
[auth setBook:#"PHP Solutions"];
[auth setYear:2010];
[_authors addObject:auth];
auth = [[Author alloc] init];
[auth setName:#"Lisa Snyder"];
[auth setBook:#"PHP security"];
[auth setYear:2011];
[_authors addObject:auth];
auth = [[Author alloc] init];
[auth setName:#"Rachel Andrew"];
[auth setBook:#"CSS3 Tips, Tricks and Hacks"];
[auth setYear:2012];
[_authors addObject: auth];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_authors count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"AuthorCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell != nil)
{
cell = [[UITableViewCell alloc]
initWithStyle: UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Author *currentAuthor = [_authors objectAtIndex:[indexPath row]];
[[cell textLabel] setText: [currentAuthor name]];
NSLog(#"%#", [currentAuthor name]);
return cell;
}
#end
Since you made the table view with its cell in the storyboard, you don't need the if (cell == nil) clause at all. You also need to call [self.tableView reloadData] as the last line in viewDidLoad.

Resources