I have a UITableView and it refuses to show any data, Xcode isn't showing any errors or warnings. Not sure why this is because the same code was working in a different app (obviously the names of array and tableview were different). I have the delegate and datasource both set as the view view-controller. If there is anything i missed please tell me!
Here is my code:
#import "ViewController.h"
#interface UIViewController ()
#end
#implementation ViewController
#synthesize CafeTableView;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self performSelector:#selector(RetriveData)];
[CafeTableView reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)RetriveData {
PFQuery *query = [PFQuery queryWithClassName:#"CafeList"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
NSLog(#"%#",objects);
NSLog(#"Successfully retrieved %d Cafes.", objects.count);
cafeListArry = [[NSArray alloc] initWithArray:objects];
}else{
UIAlertView *theAlert = [[UIAlertView alloc] initWithTitle:#"Error"
message:(#"There has been an error loading the Cafe List Please Try Again!")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[theAlert show];
NSLog(#"%#",error);
}
}];
[CafeTableView reloadData];
}
//-------------------TABLE VIEW-----------------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return cafeListArry.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CafeCell";
CafeListCell *cell = [CafeTableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
PFObject *tempObject = [cafeListArry objectAtIndex:indexPath.row];
cell.title.text = [tempObject objectForKey:#"CafeName"];
cell.detail.text = [tempObject objectForKey:#"NumberOfStars"];
return cell;
}
#end
Move your call to reloadData inside the block as others have suggested and change the if condition as follows:
- (void)RetriveData {
PFQuery *query = [PFQuery queryWithClassName:#"CafeList"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (objects) {
NSLog(#"%#",objects);
NSLog(#"Successfully retrieved %d Cafes.", objects.count);
cafeListArry = [[NSArray alloc] initWithArray:objects];
[CafeTableView reloadData]; // HERE
}else{
UIAlertView *theAlert = [[UIAlertView alloc] initWithTitle:#"Error"
message:(#"There has been an error loading the Cafe List Please Try Again!")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[theAlert show];
NSLog(#"%#",error);
}
}];
}
Also, as suggested by Lyndsey in the comments, change the following line
cell.detail.text = [tempObject objectForKey:#"NumberOfStars"];
to
cell.detail.text = [[tempObject objectForKey:#"NumberOfStars"] stringValue];
because you said that it's a number, not a string.
Please check the delegates are connected in xib file or not if not then please connect properly and please call the [tableview reloadData]; method at the time when you want bind the data with table
Related
I have a tableview that is full of current user data that is stored in parse. I want to be able to click on the cell of the parse data and be able to edit that data in a edit screen (which is just going to be the screen where you save the data from) then be able to save it and it update in the parse class on the cloud. I saw this code on the parse developer website regarding updating objects Updating Objects Here
PFQuery *query = [PFQuery queryWithClassName:#"GameScore"];
[query getObjectInBackgroundWithId:#"xWMyZ4YEGZ"
block:^(PFObject *gameScore, NSError *error) {
gameScore[#"cheatMode"] = #YES;
gameScore[#"score"] = #1338;
[gameScore saveInBackground];
}];
But the problem is that in the
[query getObjectInBackgroundWithId:#"xWMyZ4YEGZ"
block:^(PFObject *gameScore, NSError *error)
Is a query by the specific ObjectId that is stated. How can I change this so that when a user clicks on the tableview cell the query runs by that specific ObjectId in parse so that I can edit the strings associated with the ObjectId. Any tutorials or guidance is really appreciated!
Here is my Tableview.m
#implementation ViewController
- (id)initWithCoder:(NSCoder *)aCoder
{
self = [super initWithCoder:aCoder];
if (self) {
// Custom the table
// The className to query on
self.parseClassName = #"rep";
// The key of the PFObject to display in the label of the default cell style
self.textKey = #"name";
// Whether the built-in pull-to-refresh is enabled
self.pullToRefreshEnabled = YES;
// Whether the built-in pagination is enabled
self.paginationEnabled = NO;
// The number of objects to show per page
//self.objectsPerPage = 10;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(refreshTable:)
name:#"refreshTable"
object:nil];
{
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:#"Delete Cannot Be Undone" message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[Alert show];
}
}
- (void)refreshTable:(NSNotification *) notification
{
// Reload the recipes
[self loadObjects];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"refreshTable" object:nil];
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (PFQuery *)queryForTable
{
PFQuery *query = [PFQuery queryWithClassName:#"rep"];
[query whereKey:#"user" equalTo:[PFUser currentUser]];
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
static NSString *simpleTableIdentifier = #"RepCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
// Configure the cell
UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
nameLabel.text = [object objectForKey:#"name" ];
UILabel *time = (UILabel*) [cell viewWithTag:102];
time.text = [object objectForKey:#"time"];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
// Remove the row from data model
PFObject *objectToDel = [self.objects objectAtIndex:indexPath.row];
[objectToDel deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:#"Item Was Deleted Successfully. Pull Down to Refresh Tab" message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[Alert show];
[self loadView];
}
];
}
- (void) objectsDidLoad:(NSError *)error
{
[super objectsDidLoad:error];
NSLog(#"error: %#", [error localizedDescription]);
}
I have a page where we select recipients (who are friends) to send an image to. but if no recipients are selected we can still send the message. i want it so that if no recipients are selected we can show a UIAlertView. for me its not working when i try to display an alert please see my code below.
.h
#property (nonatomic, strong) NSArray *friends;
#property (nonatomic, strong) PFRelation *friendsRelation;
#property (nonatomic, strong) NSMutableArray *recipients;
- (IBAction)send:(id)sender;
.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.recipients = [[NSMutableArray alloc] init];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.friendsRelation = [[PFUser currentUser] objectForKey:#"friendsRelation"];
PFQuery *query = [self.friendsRelation query];
[query orderByAscending:#"username"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(#"Error %# %#", error, [error userInfo]);
}
else {
self.friends = objects;
[self.tableView reloadData];
}
}];
//display camera modally etc......
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
PFUser *user = [self.friends objectAtIndex:indexPath.row];
cell.textLabel.text = user.username;
if ([self.recipients containsObject:user.objectId]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView deselectRowAtIndexPath:indexPath animated:NO];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
PFUser *user = [self.friends objectAtIndex:indexPath.row];
if (cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[self.recipients addObject:user.objectId];
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
[self.recipients removeObject:user.objectId];
}
NSLog(#"%#", self.recipients);
}
here is the part where i try to display my alert
- (IBAction)send:(id)sender {
if (!self.recipients) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Select some friends" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
} else {
[self uploadMessage];
//we upload the message in method to parse.com
}
}
it does not seem to show for some reason so we can send messages to no one. how can i show the alert view?
Try this. Check objects of recipients is equal to 0 or not.
- (IBAction)send:(id)sender {
if ([self.recipients count]==0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Select some friends" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
} else {
[self uploadMessage];
//we upload the message in method to parse.com
[self.tabBarController setSelectedIndex:1];
}
}
The problem with your code is the condition that you are checking::
if (!self.recipients)
here self.recipients will always give true value as it will look for memory address of this object, which you have assigned to it in your viewDidLoad method.
You have to check for the count of the array in your scenario.
I have created an object and saved it to the backend named NewCar and there are 4 strings attached to which are year, make, model, horsepower I'm having troubles pulling the data from parse and placing it into my table here is a few pieces of my code.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
PFQuery *query = [PFQuery queryWithClassName:#"NewCar"];
[query whereKey:#"year" equalTo:[[PFUser currentUser] objectId]];
[query orderByAscending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
} else {
self.cars = objects;
[self.tableView reloadData];
}
}];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.cars count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"garageCell";
garageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[garageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.usernameDisplay.text = [[PFUser currentUser] objectForKey:#"username"];
//I need to display the year, make and model below here.
cell.carYearLabel.text = [[PFObject objectWithClassName:#"NewCar"] objectForKey:#"year"];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 236;
}
I am able to display the username in my custom cell, but can't figure out how to display the year, make and model values. Any help would be much appreciated.
I have been looking through the documentation in Parse and can't seem to figure it out just in case you are wondering if I tried there.
I also want to add in the code where I added the object to Parse this might help in figuring this out as well.
- (IBAction)save:(id)sender {
NSString *year = self.carYear.text;
NSString *make = self.carMake.text;
NSString *model = self.carModel.text;
NSString *horsepower = self.carHorsepower.text;
if ([year length] == 0 || [make length] == 0 || [model length] == 0 || [horsepower length] == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:#"You might have missed a field" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
} else {
PFObject *newCar = [PFObject objectWithClassName:#"NewCar"];
newCar[#"year"] = year;
newCar[#"make"] = make;
newCar[#"model"] = model;
newCar[#"horsepower"] = horsepower;
[newCar saveInBackground];
[self.navigationController popToRootViewControllerAnimated:YES];
}
}
Okay so instead of using
cell.carYearLabel.text = [[PFObject objectWithClassName:#"NewCar"] objectForKey:#"year"];
You can use the following
cell.carYearLabel.text = [self.cars objectForKey:#"NewCar"] valueForKey:#"year"];
This question has been successfully answered; thank you to jsksma2.
I cannot get my data to fill the rows in my TableView, even though I get the data back properly and can hard-code the tableview to display a static amount of dummy text. I have a hunch my issue relates to initWithStyle vs initWithCoder for subclassed UITableViewCells.
In a subclass of UITableViewController called "GiveItemsTableViewC", during viewDidLoad I am querying Parse for objects each called "PFGiveItem". I get these back and add each one to a global variable, a mutable array called "myGiveItems". I log these, and I get what I am looking for, so that part is working.
GiveItemsTableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
PFQuery *query = [PFQuery queryWithClassName:#"giveItem"];
[query whereKey:#"giver" equalTo:[PFUser currentUser]];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
self.myGiveItems = [[NSMutableArray alloc]init];
for (PFObject *object in objects) {
PFGiveItem *newGiveItem = [[PFGiveItem alloc]init];
newGiveItem.giveItemName = object[#"giveItemTitle"];
newGiveItem.giveItemImage = object[#"giveItemPhoto"];
[self.myGiveItems addObject:newGiveItem];
}
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}
Now I am trying to load each one of these giveItems into a TableView object, using custom TableViewCells each called "GiveItemCell."
GiveItemCell.m
#implementation JFGiveItemCell
#synthesize giveItemImageView = _giveItemImageView;
#synthesize giveItemLabel = _giveItemLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
Back in the table view controller, I return one section for the table view.
And when I include a static number for the rowsInSection, I can output test values to each cell. If I execute the code below, I will get a tableView with cells with the label of "Test", as per the upcoming cellForRowAtIndexPath method. So it works with that test, but obviously I'm looking to dynamically load the proper information.
GiveItemsTableViewController
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 4;
}
- (JFGiveItemCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"Cell";
JFGiveItemCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil){
cell = [[JFGiveItemCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
// PFGiveItem *giveItem = self.myGiveItems[indexPath.row];
// cell.giveItemLabel.text = giveItem.giveItemName;
cell.giveItemLabel.text = #"Test";
return cell;
}
It looks like you're forgetting to call [tableView reloadData] in the callback of your block method:
- (void)viewDidLoad
{
[super viewDidLoad];
PFQuery *query = [PFQuery queryWithClassName:#"giveItem"];
[query whereKey:#"giver" equalTo:[PFUser currentUser]];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
self.myGiveItems = [[NSMutableArray alloc]init];
for (PFObject *object in objects) {
PFGiveItem *newGiveItem = [[PFGiveItem alloc]init];
newGiveItem.giveItemName = object[#"giveItemTitle"];
newGiveItem.giveItemImage = object[#"giveItemPhoto"];
[self.myGiveItems addObject:newGiveItem];
}
[self.tableView reloadData];
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}
Also, I second #CrimsonChris in saying that you need to set your dataSource methods properly:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.myGiveItems.count
}
There are a couple of problems...
Your numberOfRowsInSection should return the size of your myGiveItems array.
You need to tell your table view to reload when you finish loading your items asynchronously.
You don't need to implement number of sections, it defaults to 1.
When I run the following code, nothing appears on my UITableView. I created a global NSMutableArray for storing the results of a query on Parse, but I can't manage to use that array to load the cells on the UITableView.
Thanks!
#import "ViewController.h"
#import "MenuViewController.h"
#import "Parse/Parse.h"
#interface ViewController ()
#end
#implementation ViewController {
CLLocationManager *locationManager;
}
#synthesize eventTableView;
#synthesize eventTableViewCell;
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadEvents];
}
- (void) loadEvents
{
eventNames = [[NSMutableArray alloc] init];
PFQuery *event_query = [PFQuery queryWithClassName:#"Event"];
[event_query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
NSLog(#"Successfully retrieved %lu scores.", (unsigned long)objects.count);
for (PFObject *object in objects) {
[eventNames addObject:[object objectForKey:#"event_name"]];
NSLog(#"%#", [object objectForKey:#"event_name"]);
NSLog(#"%lu", (unsigned long)eventNames.count);
}
} else {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [eventNames count];
}
- (UITableViewCell *)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MainCell"];
}
NSString *cellText = [NSString stringWithFormat:#"%#",eventNames[indexPath.row]];
NSLog(#"%#", eventNames[indexPath.row]);
cell.textLabel.text = cellText;
return cell;
}
#end
Copy and paste the following loadEvents method
- (void) loadEvents
{
eventNames = [[NSMutableArray alloc] init];
PFQuery *event_query = [PFQuery queryWithClassName:#"Event"];
[event_query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
NSLog(#"Successfully retrieved %lu scores.", (unsigned long)objects.count);
for (PFObject *object in objects) {
[eventNames addObject:[object objectForKey:#"event_name"]];
NSLog(#"%#", [object objectForKey:#"event_name"]);
NSLog(#"%lu", (unsigned long)eventNames.count);
}
[eventTableView reloadData];
} else {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}
Every time you asynchronously fetch data for table view, you have to reload the whole table or the changed sections.
I'm guessing that the result from findObjectsInBackground returned after the tableview has already displayed. Did the NSLog print out the results that you expected?
One thing to try is to add a
[eventTableView reloadData];
after the for loop , which will tell the tableview to reload the data again.