I have fetched Json with JSONKit from url to NSDictionary in initWithNibName
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:jsonUrl]];
JSONDecoder *jsonKitDecoder = [JSONDecoder decoder];
jsonDic = [jsonKitDecoder parseJSONData:jsonData]; // NSDictionary *jsonDic
NSLog(@"Json Dictionary Fetched %@", jsonDic); // Display the Json fine :-)
NSLog(@"Dictionary Count %i", [jsonDic count]); // Display the Dic count fine :-)
array = [jsonDic objectForKey:@"courses"]; // NSArray *array
NSLog(@"Courses Found %@", array); // Display the array fine :-)
NSLog(@"Courses Count %i", [array count]);
Here is the Json
{ "name":"Name 1" , "courses": [
{ "title":"Course 1" , "desc":"This is course 1" },
{ "title":"Course 2" , "desc":"This is course 2" },
{ "title":"Course 3" , "desc":"This is course 3" } ]
}
I dragged a tableview to xib. set IBOutlet UITableview tblView to the tableview in Connections on Interface Builder and aslo the the tableview dataSource and delegate to FilesOwner
manually added the tableview events as
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int cnt = [array count]; // CRASHES HERE Remeber returning 1; still why ?
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
int indx = [indexPath indexAtPosition:1];
/* THESE ARE ALL COMMENTED
NSString *key = [[jsonDic allKeys] objectAtIndex:indx];
NSString *value = [jsonDic objectForKey:key];
cell.textLabel.text = value;
/* / THESE ARE ALL COMMENTED
NSDictionary *eachItem = [array objectAtIndex:indx];
cell.textLabel.text = [eachItem objectForKey:@"title"];
// */
cell.textLabel.text = @"My Title"];
return cell;
}
Someone please help me on this. I need to display the Courses on tableview.
Your array object is probably deallocated leading to a crash (EXEC_BAD_ACCESS?) if you send a message (here count) to it. From the line
It seems like it is autoreleased, you should retain it.
EDIT:
You can retain it by:
Setting it as a retain property
and using the accessor
which automatically releases the old value and retains the new one. Or by retaining it explicitely
then you must not forget to release it when you are done or you will leak memory. You should read the Advanced Memory Management Programming Guide, it gives you a thorough explanation, and it is quite crucial that you understand the basic techniques.