Brittany Brittany - 1 month ago 11
iOS Question

How can I stop my UITableView from crashing when the array is empty?

When my app's user signs up for an account, the tableView starts out empty (as no data has been added by the user). How can I stop the app from crashing when the soon-to-be populated array is empty? So far, I've tried displaying a view when the table/array is empty, but the crash still occurs...

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

return [self.storageData count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *DoctorsTableIdentifier = @"StorageItemTableViewCell";

StorageItemTableViewCell *cell = (StorageItemTableViewCell *)[tableView dequeueReusableCellWithIdentifier:DoctorsTableIdentifier];
if (cell == nil)

{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"StorageItemTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}

if (self.storageData > 0) {

noitemsView.hidden = YES;

NSDictionary *tmp = [self.storageData objectForKey:[NSString stringWithFormat:@"%d",(long)indexPath.row]];


[[cell itemName] setText:(NSString *)[tmp objectForKey:@"title"]];

NSString *title = [tmp objectForKey:@"title"];
[[cell itemName] setText:title];


NSDictionary *node = [self.descripData objectAtIndex:indexPath.row];
[[cell itemDescrip] setText:[node objectForKey:@"body"]];
NSLog(@"%@", self.descripData);

NSString *secondLink = [[self.descripData objectAtIndex:indexPath.row] objectForKey:@"photo"];

[cell.itemPhoto sd_setImageWithURL:[NSURL URLWithString:secondLink]];

NSLog(@"%@",secondLink);


}
else {
noitemsView.hidden = NO;
}
return cell;
}

Answer

You need to update your numberOfRows Delegate method

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   if ([self.storageData count] > 0 && self.descripData.count>0)
    {
      return [self.storageData count];
    }
     else
     return 1;
 }

Also modify the code as below

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
----------
        if (self.storageData.count > 0 && self.descripData.count>0) {
------------//Instead of self.storageData>0
        }
----------
}

It fixes the crash issue if storageData is empty..!

Comments