table view numberOfRowsInSection returning 0 - ios

I have a table view which I wish to populate with data stored in parse.com.
However nothing loads in my table view. I've done a few breakpoints and NSLog's and found that my numberOfRowsInSection method is always returning 0.
Here is my code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int num = [_totalDistance count];
NSLog(#"num = %d", num);
return [_totalDistance count];
}
activityTypeArray is populated from data collected from parse.com in my viewDidLoad method, is it possible this is the problem?
Here is where _totalDistance is populated:
- (void)viewDidLoad
{
_activityTypeArray = [NSMutableArray array];
_totalDistance = [NSMutableArray array];
PFQuery *activityQuery = [PFQuery queryWithClassName:#"Activities"];
[activityQuery whereKey:#"triathlete" equalTo:[PFUser currentUser]];
[activityQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
for (PFObject *object in objects) {
;
NSString *activityType = [object objectForKey:#"activityType"];
[_activityTypeArray addObject:activityType];
NSString *totalDistance = [object objectForKey:#"totalDistance"];
[_totalDistance addObject:totalDistance];
NSLog(#" total distance %#", _totalDistance);
int num = [_activityTypeArray count];
NSLog(#"num = %d", num);
}
}
}];
}
Thanks

Modify your code to reload tableView data. Otherwise your tableView won't know you have data to show.
[activityQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
for (PFObject *object in objects) {
;
NSString *activityType = [object objectForKey:#"activityType"];
[_activityTypeArray addObject:activityType];
NSString *totalDistance = [object objectForKey:#"totalDistance"];
[_totalDistance addObject:totalDistance];
NSLog(#" total distance %#", _totalDistance);
int num = [_activityTypeArray count];
NSLog(#"num = %d", num);
// line added
[self.tableView reloadData];
}
}
}];

You are logging another value (_activityTypeArray count) than you are returning as result (_totalDistance count)
So the NSLog statement cannot help

Related

UISwitch changing object parse objective c

I am working on a app that you can change when a item on the menu is in stock or out of stock.
I have it now so it changes the UISwitch to on or off when it loads the screen. I need each switch to change a NSString in parse that makes it one or zero.One meaning that it is on zero meaning its off.
I am fairly new to objective c and parse so if any one could help me get a start on this problem that would be great!
You might use something like that:
PFQuery *query = [PFQuery queryWithClassName:#"YourClass"];
[query whereKey:#"user" equalTo:[PFUser currentUser]];
[query getFirstObjectInBackgroundWithBlock:^(PFObject * yourClass, NSError *error) {
if (!error) {
// Found yourClass object
[yourClass setObject:isInStock forKey:#"isInStock"];
// Save
[yourClass saveInBackground];
} else {
// Did not find any yourClass object for the current user
NSLog(#"Error: %#", error);
}
}];
NSArray *listObjects = .... (loading from Server) // List of PFObject
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
PFObject *object = [listObjects objectAtIndex:indexPath.row];
YourCell *cell = .....
if ([[object valueForKey:#"sandwichesOutofstock"] intValue] == 1)
cell.switch.on = true;
else
cell.switch.on = false;
cell.switch.tag = 500 + index.row;
[cell.switch addTarget:self action:#selector(switchTouch:) forControlEvents:UIControlEventTouchUpInside]
.........
}
(IBAction)switchTouch:(UISwitch *)switch{
long index = switch.tag - 500;
PFObject *object = [listObjects objectAtIndex:index];
if(switch.on)
[object setValue:#"1" ForKey:#"sandwichesOutofstock"];
else{
[object setValue:#"0" ForKey:#"sandwichesOutofstock"];
}
[object saveInBackground];
[self.tableView reloadRowsAtIndexPaths:[NSIndexPath indexPathForRow:index inSection:0] withRowAnimation:UITableViewRowAnimationNone];
}
You could assign a reference of the PFObject to the cell. Then when the switch changes just get the cell's object and make the change.

how to get object by key and value

I have an object called masterMessages filled with objects called messages. Each message object has five keys:
objectId
senderId
senderName
messageBody
timestamp
Basically what I am doing now is querying all the messages sent to my user in this object called masterMessages. Then i'm using:
self.senderIds = [masterMessages valueForKeyPath:#"#distinctUnionOfObjects.senderId"];
to get all the different sender ids (senderId) in an array called senderIds. With this I will populate my conversations table. But i want to populate it with the sender names (senderName) and not the senderIds. I only do it this way in case two users have the same name.
I am trying to find:
How do I say "get valueForKey:#"senderName" for this senderId
and
is there a better way to populate my conversations table?
Here is my code:
note: im using parse.com
-(void)viewWillAppear:(BOOL)animated{
NSString *userId = [[PFUser currentUser] objectId];
PFQuery *query = [PFQuery queryWithClassName:#"lean"];
[query whereKey:#"recipientId" equalTo:userId];
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
else {
// We found messages!
masterMessages = objects;
NSLog(#"self.messages = %#", masterMessages);
self.senderIds = [masterMessages valueForKeyPath:#"#distinctUnionOfObjects.senderId"];
NSLog(#"self.senderIds = %#", self.senderIds);
[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.senderIds count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
NSLog(#"self.senderIds = %#", self.senderIds);
NSString *senderDisplayName = [self.senderIds objectAtIndex:indexPath.row];
NSLog(#"sender = %#", senderDisplayName);
cell.textLabel.text = senderDisplayName;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
selectedId = [self.senderIds objectAtIndex:indexPath.row];
[self performSegueWithIdentifier:#"ShowMissionMessage" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"ShowMissionMessage"]) {
[segue.destinationViewController setHidesBottomBarWhenPushed:YES];
MissionChat *missionchatviewcontroller = (MissionChat *)segue.destinationViewController;
missionchatviewcontroller.selectedId = selectedId;
missionchatviewcontroller.masterMessages = masterMessages;
}
}
There are a few issues in the question, one is how to dereference PFObjects, which we took care of on another thread. The rest of this question is about (a) how to use parse objects to build a datasource to support a tableview, and a harder one (b) how to get information from related objects.
Starting with (b), the harder one: There are a few ways to relate objects. Your choice a string-typed column containing the related object id, is intuitive (especially if you have an SQL background), but the least advisable. The better (best) way to model a one-to-one or small one-to-many relation is with a pointer (or array of pointers if one-to-many).
So I think your senderId and recipientId string columns should be replaced by pointer-typed columns called sender and recipient. The huge advantage of this is the ability to eagerly fetch those pointed-to objects on the message (or "lean" in your terms) query.
Having made that change, you're new improved query looks like this:
PFQuery *query = [PFQuery queryWithClassName:#"lean"];
// notice the first change for the better here:
[query whereKey:#"recipient" equalTo:[PFUser currentUser]];
[query orderByDescending:#"createdAt"];
// notice the really valuable feature here:
[query includeKey:#"sender"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
// using the array of PFObjects understanding from your other question...
for (PFObject *pfObject in objects) {
NSString *messageBody = [pfObject objectForKey:#"messageBody"];
// these lines here are the punch line:
PFUser *sender = [pfObject objectForKey:#"sender"];
NSString *senderName = [sender username];
NSLog(#"The message %# was sent by %#", messageBody, senderName);
}
}];
The important thing to notice above is that we were able to ask resulting objects for the #"sender" column, and, because you've changed it to a pointer, and because you've done an includeKey on the query, that complete object (e.g. including the PFUser username) is now fetched.
Now the easy question (a). Now that you have the data right from the server, the datasource for the table is nothing more than the returned objects. In other words, throw away the the senderIds array and replace it with:
#property(nonatomic, strong) NSArray *messages;
Your find block becomes trivial:
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.messages = objects;
}];
Answer messages.count for numberOfRowsInSection, and then pick what you need from the objects in cellForRowAtIndexPath...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
PFObject *message = self.messages[indexPath.row];
NSString *messageBody = [message objectForKey:#"messageBody"];
PFUser *sender = [message objectForKey:#"sender"];
NSString *senderName = [sender username];
cell.textLabel.text = senderName;
return cell;
}
function findObjectByKey(array, key, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][key] === value) {
return array[i];
}
}
return null;
}
var obj = findObjectByKey(objArray, 'id', 3);
//ES6
var obj = objArray.find(function (obj) { return obj.id === 3; });
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
var result = getObjects(obj, 'category_id', valu.category_id);
console.log(result);

Autocomplete text field in iOS not working

i am newbie in iOS development, i want to add autocomplete textfield in my ap i write a code for that like as
- (void)viewDidLoad
{
[self get data];
}
-(void)getdata
{
NSMutableArray *allObjects = [NSMutableArray array];
NSUInteger limit = 1000;
__block NSUInteger skip = 0;
PFQuery *query = [PFQuery queryWithClassName:#"MapInfo"];
[query setLimit: limit];
[query setSkip: skip];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
[allObjects addObjectsFromArray:objects];
if (objects.count == limit) {
skip += limit;
[query setSkip: skip];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
[allObjects addObjectsFromArray:objects];
self.qpinname=[allObjects valueForKey:#"GPIN"];
self.locationarray=[allObjects valueForKey:#"Location"];
self.latitude=[self.locationarray valueForKey:#"lat"];
self.longitude=[self.locationarray valueForKey:#"lng"];
self.address=[allObjects valueForKey:#"Address"];
NSLog(#"Address %#",self.address);
self.usernameArray=[allObjects valueForKey:#"AddedBy"];
}];
}
}
else
{
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}
then i got my data array and i want to show it on my table view like as
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring
{
[self.autoaddress removeAllObjects];
for(NSString *curString in self.address)
{
NSRange substringRange = [curString rangeOfString:substring];
if (substringRange.location == 0) {
[self.autoaddress addObject:curString];
}
}
[_autocompleteTableView reloadData];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
_autocompleteTableView.hidden = NO;
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section
{
return self.autoaddress.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
static NSString *AutoCompleteRowIdentifier = #"AutoCompleteRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier] ;
}
cell.textLabel.text = [self.autoaddress objectAtIndex:indexPath.row];
return cell;
}
then i got error in code
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring
{
[self.autoaddress removeAllObjects];
for(NSString *curString in self.address)
{
NSRange substringRange = [curString rangeOfString:substring];
if (substringRange.location == 0) {
[self.autoaddress addObject:curString];
}
}
[_autocompleteTableView reloadData];
}
Here i got error in line NSRange substringRange = [curString rangeOfString:substring]; -[NSNull rangeOfString:]: unrecognized selector sent to instance i find it in google but i not get solution please help me for this
thanks.
Your self.address property is probably NSNull or it contains NSNull if it is an array. You can check if object is NSNull the following way:
if(![object isEqual:[NSNull null]])
{
//do something if object is not equals to [NSNull null]
}
The code is from this answer.
EDIT: If you use NSMutableArray you can call the method [self.address removeObjectIdenticalTo:[NSNull null]] to remove all NSNull objects from the array after self.address=[allObjects valueForKey:#"Address"];

Get an array from Parse query [duplicate]

This question already has an answer here:
Pass data from Parse tableview to WatchKit
(1 answer)
Closed 8 years ago.
I'm using Parse to create this table view, and am trying to figure out how to get the Parse table data into an array, so I can pass it into the WatchKit InterfaceController to show the exact same thing?
So I want to show in the WatchKit interface exactly what shows in the iPhone interface.
Here is what I have, let me know if I can add anything that would be helpful:
TableVC.m:
- (id)initWithCoder:(NSCoder *)aCoder
{
self = [super initWithCoder:aCoder];
if (self) {
self.parseClassName = #"na";
self.textKey = #"dateTime";
self.pullToRefreshEnabled = YES;
self.paginationEnabled = NO;
}
return self;
}
- (PFQuery *)queryForTable
{
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
static NSString *simpleTableIdentifier = #"RecipeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
UILabel *homeLabel = (UILabel*) [cell viewWithTag:101];
homeLabel.text = [object objectForKey:#"test"];
UILabel *dateLabel = (UILabel*) [cell viewWithTag:102];
dateLabel.text = [object objectForKey:#"dateTime"];
return cell;
}
Parse data:
TableVC.m:
I already have the basic WatchKit files and Storyboard set up. I hard coded an array to test that it was generally working. But now I just need to get the data from Parse into there, and not sure if I need to do a query and then turn that into a public array?
EDIT:
Here is my query:
PFQuery *query2 = [PFQuery queryWithClassName:#"nba"];
[query2 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// The find succeeded.
NSLog(#"Objects 2: %#", objects);
}
} else {
// Log details of the failure
NSLog(#"Error 2: %# %#", error, [error userInfo]);
}
}];
Here is my NSLog:
NSLog(#"Objects 2: %#", objects);
Console:
2015-02-09 21:06:30.845 SimpleTable[8373:1284663] Objects 2: (
"<na: 0x7ff3f8e40880, objectId: cOrjeAmwJh, localId: (null)> {\n away = Cav;\n date = \"04/19/2015\";\n dateTime = \"April 19, 2015, 16:00\";\n gNumber = 1;\n home = Bul;\n matup = \"Ca\";\n ro = \"Ro \";\n test = \"Test 2\";\n tv = T;\n}",
If you need the array, fetch it asynchronously in a method outside of the queryForTable method, get it like this:
PFQuery *query = [self queryForTable];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// objects is the array for this table
NSMutableArray *array = [#[] mutableCopy];
for (PFObject *object in objects) {
NSLog(#"we got an object with dateTime = %#", [object objectForKey:#"dateTime"]);
[array addObject:[object objectForKey:#"dateTime"]];
// you can prove this with any of your keys: away, number, home, mat up, etc.
}
}
}];
if you just want to pass the objects into an array you can do so like this or a variation of:
- (PFQuery *)queryForTable
{
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
self.someArray = [query findObjects];
return query;
}
REFERNECE

UitableViewCell not properly displaying accessories

I have a friendslist view controller that allows the user to see pending friend requests. The isPending method is first used to see if a particular user has a pending friend request with the current user.
-(BOOL)isPending:(PFUser *)user
{
for (PFUser *pending in self.Pending){
if ([pending.objectId isEqualToString:user.objectId]){
return YES;
}
}
return NO;
}
This method is called within cellForRowAtIndexPath method inside the TableViewController. THe problem that I am experiencing is that If I run the query inside the tableViewController users who are pending are properly displayed. When I moved the query to a singleton datasource class, I have setup a delegate method that is called when data is returned from the query.
-(void)pendingFriendsQuarryDidFinishWithData{
self.Pending = [NSMutableArray arrayWithArray:dataHolder.getPendingFriendsList];
[self.tableView reloadData];
}
Calling reloadData does not cause the checkmarks to appear next to the users names.
EDIT: Here is the code for cellForRowAtIndexPath. It does not change with the singleton.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
// Configure the cell...
PFUser *user = [self.allUsers objectAtIndex:indexPath.row];
cell.textLabel.text = user.username;
cell.detailTextLabel.text = user.email;
cell.imageView.image = [UIImage imageNamed:#"Treehouse.png"];
if([self isPending:user]){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
return cell;
}
What does change is how the data is obtained. Without the singleton here is the code
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
/*
self.currentUser = [PFUser currentUser];
if (self.currentUser != nil){
PFQuery *userQuery = [PFUser query];
PFQuery *pendingUser = [PFUser query];
PFRelation *friendRelation = [self.currentUser relationForKey:#"friendRelation"];
PFQuery *existingFriends = [friendRelation query];
PFQuery *pendingFriends = [PFQuery queryWithClassName:#"FriendRequest"];
userQuery.cachePolicy = kPFCachePolicyCacheThenNetwork;
pendingFriends.cachePolicy = kPFCachePolicyCacheThenNetwork;
[pendingFriends whereKey:#"fromUser" equalTo:self.currentUser.objectId];
[pendingFriends whereKey:#"status" equalTo:#"Pending"];
[userQuery whereKey:#"objectId"doesNotMatchKey:#"toUser" inQuery:pendingFriends];
[userQuery whereKey:#"objectId" doesNotMatchKey:#"objectId" inQuery:existingFriends];
[userQuery orderByAscending:#"username"];
[userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error){
NSLog(#" Error %# %#", error, [error userInfo] );
}else{
NSLog(#"All Users Array Starts Here: %#", objects);
self.allUsers = objects;
[self.tableView reloadData];
}
}];
[pendingUser whereKey:#"objectId" matchesKey:#"toUser" inQuery:pendingFriends];
[pendingUser orderByAscending:#"username"];
[pendingUser findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error){
NSLog(#"%# %#", error, [error userInfo]);
}else{
[self.Pending addObjectsFromArray:objects];
NSLog(#"Pending Friends Array Stars here: %#", self.Pending);
}
}];
}
*/
}
With singleton
- (void)viewDidLoad
{
dataHolder = [DataHolder sharedInstance];
dataHolder.delegate = self;
self.friends = [NSMutableArray new];
self.allUsers = [NSMutableArray new];
self.allUsers = [NSMutableArray arrayWithArray:dataHolder.getAllUsersWithQuarry];
self.Pending = [NSMutableArray new];
self.Pending = [NSMutableArray arrayWithArray:dataHolder.getPendingFriendsListWithQuarry];
[super viewDidLoad];
NSLog(#"Now in Connection Editor");
}
-(void)allUsersQuarryDidFinishWithData{
self.allUsers = [NSMutableArray arrayWithArray:dataHolder.getAllUsers];
[self.tableView reloadData];
}
-(void)pendingFriendsQuarryDidFinishWithData{
self.Pending = [NSMutableArray arrayWithArray:dataHolder.getPendingFriendsList];
[self.tableView reloadData];
}
Silly question, did you set the datasource of your tableviewcontroller to point to your singleton datasource?
tableview.datasource = [your singleton class instance]
and make sure that you step into it in the debugger.
Hope this helps.

Resources