Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting allKeys from NSDictionary returns EXC_BAD_ACCESS

I am trying to send an NSDictionary to a TableViewController, the data originally comes from a .plist file. I simply want to send an object that exists further down the hierarchy to new TableViewController. But problems occur when I try to count the number of items in numberOfSectionsInTableView.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {   
// Gets the dictionary for the currently selected row
NSDictionary *dict = [[data objectForKey:[[data allKeys] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];

// Checks if the key "Room" exists
if([dict objectForKey:@"Room"]) {
    SalesFairSessionTableViewController *sessionViewController = [[SalesFairSessionTableViewController alloc] init];

    // Sets the data in the subview Controller
    [sessionViewController setData:[dict objectForKey:@"Room"]];

    // And the title
    [sessionViewController setTitle:[dict objectForKey:@"Title"]];

    // Problem is here... returns EXC_BAD_ACCESS
    NSLog(@"%@", [[[dict objectForKey:@"Room"] allKeys] count]);

    [self.navigationController pushViewController:sessionViewController animated:YES];
    [sessionViewController release];
}
}

If I just use allKeys like this:

NSLog([[dict objectForKey:@"Room"] allKeys]);

It returns ("Item 1", "Item 2") in the console.

But when I add the ”count” method like this:

NSLog(@"%@", [[[dict objectForKey:@"Room"] allKeys] count]);

I just get: Program received signal: “EXC_BAD_ACCESS”.

What am I missing here?

like image 290
kroofy Avatar asked Dec 13 '22 17:12

kroofy


2 Answers

NSLog(@"%@", [[[dict objectForKey:@"Room"] allKeys] count]);

count gives an int, but you print with %@, expecting a pointer to an object. Use %d instead.

like image 75
Eiko Avatar answered Feb 02 '23 00:02

Eiko


As your code currently stands, you're telling the NSLog string to expect an object. count returns an NSInteger, hence the error. To fix, change this line:

NSLog(@"%@", [[[dict objectForKey:@"Room"] allKeys] count]);

to this:

NSLog(@"%i", [[[dict objectForKey:@"Room"] allKeys] count]);
like image 21
Sam Ritchie Avatar answered Feb 02 '23 01:02

Sam Ritchie