I have a bug that is driving me crazy. I have an NSArray called questions. The array is being populated by a JSON response. I’m trying to use it to populate the table view.
in my header file I’m defining questions like this
@interface OneViewController : UITableViewController <MBProgressHUDDelegate> {
NSArray *questions;
MBProgressHUD *HUD;
}
@property (nonatomic, strong) NSArray *questions;
and in my implementation, im instantiating it like this
@synthesize questions;
when the view loads, I’m calling this function that pings my JSON service
- (void) pullQuestions {
NSMutableDictionary *viewParams = [NSMutableDictionary new];
[viewParams setValue:@"questions" forKey:@"view"];
[PythonView viewGet:viewParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
questions = responseObject;
NSLog(@"Qestions: %@", responseObject);
[self.tableView reloadData];
[HUD hide:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//ALog(@"Failure: %@", [error localizedDescription]);
}];
}
When I get a response, I trace out the response object, it is a properly formated JSON response.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"VideoFeedCell";
NSInteger count = [questions count];
NSLog(@"Count: %i", count);
for (int i = 0; i < count; i++) {
NSString* body = [questions objectAtIndex:i];
NSLog(@"Object: %@", body);
}
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"VideoFeedCell" owner:self options:nil];
// Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
cell = [topLevelObjects objectAtIndex:0];
}
return cell;
}
So as I loop through this, questions count is 4 and the first object in the array is traced out (as null). The second time it tries to execute the for loop, I get EXC_BAD_ACCESS. it’s almost like the questions array just disappears. The strangest pat is I use almost the exact same code in another project and it works fine. I even tested it with the same JSON service that I used in the other project (so I know it’s not malformed or something) and I still get this error.I’m really stuck, I fell like it must have to do either with saving the JSON response as an Array or something strange with the array it’s self being released.
Assuming you aren’t using ARC, I suspect the problem is that you are assigning the
responseObjectdirectly to thequestionsinstance variable rather than through the property. This means that you aren’t taking ownership of theresponseObjectand it is getting released when the autorelease pool is flushed.Try changing:
to:
or:
and see if that fixes things.