Second view in UITableView will not display parsed data from JSON - iphone

I have a parsed data from JSON file. It works like a charm in the first view of my UITableView. However, it displays a blank second view when I tap on an item.
MasterView.h
#interface MasterViewController : UITableViewController
{
NSArray *json;
}
#property (nonatomic, retain) NSArray *json;
#end
MasterView.m
#import "MasterViewController.h"
#import "InformationViewController.h"
#interface MasterViewController ()
#end
#implementation MasterViewController
#synthesize json;
- (void)viewDidLoad
{
[super viewDidLoad];
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://j4hm.t15.org/ios/console.php"]];
[self performSelectorOnMainThread: #selector(fetchedData:) withObject: jsonData waitUntilDone: YES];
}
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
self.json = [NSJSONSerialization JSONObjectWithData: responseData options: kNilOptions error: &error];
NSLog(#"String is %#", self.json);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [json count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.text = [[json objectAtIndex: indexPath.row] objectForKey: #"Console"];
[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
InformationViewController *informationViewController = [[InformationViewController alloc] initWithStyle:UITableViewStylePlain];
informationViewController.title = [[json objectAtIndex: indexPath.row] objectForKey: #"Console"];
informationViewController.Information = [[json objectAtIndex: indexPath.row] objectForKey: #"Model"];
NSLog(#"String is %#", informationViewController.Information);
[self.navigationController pushViewController: informationViewController animated:YES];
}
InformationView.h
#interface InformationViewController : UITableViewController
#property (nonatomic, strong) NSArray * Information;
#end
InformationView.m
#interface InformationViewController ()
#end
#implementation InformationViewController
#synthesize Information;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [[Information objectAtIndex: indexPath.row] objectForKey: #"Model"];
[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
return cell;
}

Here i Posted Another Answer Just Because i don't want to Generate Confusion.
The Project Code : http://www.cogzentappz.com/demo/iostutorial/TestJson.zip
instead of passing the Selected Value, Pass the Whole Array through NSUsedDefaults And Retrive them Using Following Code.
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
self.json = [NSJSONSerialization JSONObjectWithData: responseData options: kNilOptions error: &error];
NSLog(#"String is %#", self.json);
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *arrayObj = [[NSMutableArray alloc] init];
for(int i = 0 ; i<[self.json count] ; i++) {
[arrayObj addObject:[json objectAtIndex:i]]];
}
[standardDefaults setObject:arrayObj forKey:#"longArray"];
[arrayObj release];
}
In the Next View you can Retrive the data Using the Below method.
in ViewDidLoad of informationViewcontroller use This
//reading
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
NSArray *arrayObj = [standardDefaults objectForKey:#"longArray"];
for(int i = 0 ; i<[arrayObj count] ; i++) {
NSLog(#"String is %#",[arrayObj objectAtIndex:i]);
}
As per Your Link The Json Output is like Below :
NSArray-->NSDictionary-->NSArray-->NSDictionary-->NSArray-->NSDictionary
Go to the link : http://json.bloople.net and Post all your json output and Hit enter.
So you have to get the values According to that format.
for(int i = 0 ; i<[self.json count] ; i++) {
NSArray *info_Array=[[self.json objectAtIndex:i ]valueForKey:#"Information"];
NSLog(#"info_Array is %#", info_Array);
for(int j = 0 ; j<[info_Array count] ; j++)
{
NSLog(#"Model is %#", [[info_Array objectAtIndex:j ]valueForKey:#"Model"]);
NSArray *title_Array=[[info_Array objectAtIndex:j ]valueForKey:#"Title"];
for(int k = 0 ; k<[title_Array count] ; k++)
{
NSLog(#"Game is %#", [[title_Array objectAtIndex:k ]valueForKey:#"Game"]);
NSLog(#"Publisher is %#", [[title_Array objectAtIndex:k ]valueForKey:#"Publisher"]);
}
}
NSString *Console_string= [[dataArray objectAtIndex:i ]valueForKey:#"Console"];
NSLog(#"String is %#", Console_string);
}
NSString *Console_string= [[self.Json objectAtIndex:i ]valueForKey:#"Console"];
NSLog(#"String is %#", Console_string);
}

I think you have to reloadData after you fetch your data. Right now, you specify that the NSArrray *json is empty, since the count returns 0. Thus, you prohibit the table view from being filled. Call [tableView reloadData]; after you fetch your data.

Change your code of MaterView.m with this
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
InformationViewController *informationViewController = [[InformationViewController alloc] initWithStyle:UITableViewStylePlain];
informationViewController.title = [[json objectAtIndex: indexPath.row] objectForKey: #"Console"];
informationViewController.Information = [[json objectAtIndex: indexPath.row] objectForKey: #"Model"];
NSLog(#"String is %#", informationViewController.Information);
[self.navigationController pushViewController: informationViewController animated:YES];
}
Hope it helps you...

Related

Xcode live news feed with multiple accounts or user

Im new to xcode.
and Im creating this facebook, twitter, instagram and youtube news feed in a tableview
at first Im trying this facebook to load multiple json
#import "ViewController.h"
#import "DetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#define kQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kJSONUrl [NSURL URLWithString:#"https://www.facebook.com/feeds/page.php?id=1387524391527078&format=json"]
#define kJSONUrl1 [NSURL URLWithString:#"https://www.facebook.com/feeds/page.php?id=196934133652011&format=json"]
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#interface ViewController ()
#end
#implementation ViewController
#synthesize jsonTitles,table,jsonContent;
-(void)loadJSON:(NSData *)responseData {
NSError *error;
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray *array = [json valueForKey:#"entries"];
for (int i = 0; i < array.count; i++) {
NSArray *entry = [array objectAtIndex:i];
NSString *title = [entry valueForKey:#"title"];
NSString *content = [entry valueForKey:#"content"];
[jsonTitles addObject:title];
[jsonContent addObject:content];
}
[self.table reloadData];
}
- (void)viewDidLoad
{
self.table.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.png"]];
jsonTitles = [[NSMutableArray alloc]init];
jsonContent = [[NSMutableArray alloc]init];
dispatch_async(kQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:kJSONUrl];
[self performSelectorOnMainThread:#selector(loadJSON:) withObject:data waitUntilDone:YES];
NSData *data1 = [NSData dataWithContentsOfURL:kJSONUrl1];
[self performSelectorOnMainThread:#selector(loadJSON:) withObject:data1 waitUntilDone:YES];
});
[super viewDidLoad];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 40;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [jsonTitles count];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:#"detailSegue" sender:nil];
// NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:#"detailSegue" ascending:YES];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"detailSegue"]) {
DetailViewController *detail = segue.destinationViewController;
NSIndexPath *path = [self.table indexPathForSelectedRow];
detail.titleText = [jsonTitles objectAtIndex:path.row];
detail.contentText = [jsonContent objectAtIndex:path.row];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *tableCellID = #"tableCellID";
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableCellID];
UITableViewCell *cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:tableCellID];
NSString *myurl = #"http://graph.facebook.com/idoltap/picture";
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myurl]];
UIImage *myimage = [[UIImage alloc] initWithData:imageData];
cell.imageView.image = myimage;
// cell.imageView.image = [UIImage imageNamed:#"background.png"];
cell.textLabel.text = #"iDOLTap";
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableCellID];
}
cell.detailTextLabel.text = [jsonTitles objectAtIndex:indexPath.row];
if ([cell.detailTextLabel.text isEqual: #" "]) {
cell.detailTextLabel.text = [jsonContent objectAtIndex:indexPath.row];
}
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Is my pattern correct?
I dont know how I can load the right profile picture for each json/user and sort it by its published date.
I just want some help to fix this one in the right way.

Want to display the array values in the table

Table View:
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return [self.detailArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
tableView.delegate = self;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 5.0f, 300.0f, 30.0f)];
label.text=[NSString stringWithFormat:#"%#",[self.detailArray objectAtIndex:indexPath.row]];
label.numberOfLines = 3;
label.font = [UIFont fontWithName:#"Helvetica" size:(12.0)];
label.lineBreakMode = UILineBreakModeWordWrap;
label.textAlignment = UITextAlignmentLeft;
[cell.contentView addSubview:label];
[label release];
[self.myTableView reloadData];
return cell;
}
I want to store the detail (array value) in the tableView.I used both method numberOfRowsInSection and cellForRowAtIndexPath but the table display null. How can I display?
Make property for NSMutable array in .h
#property (nonatomic,retain) NSMutableArray *detailArray;
and synthesize it in .m
#synthesize detailArray=_detailArray;
and change this line
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
to
_detailArray=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
then use _detailArray for displaying table data.
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [_detailArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// _detailArray objects for date population.
}
Your Code :
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",startPoint,midannotation.coordinate.latitude,midannotation.coordinate.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSString *someString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// NSLog(#"data:%#",someString);
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
arr = [parsedJson objectForKey:#"routes"];
dic = [arr objectAtIndex:0];
// NSLog(#"ALL KEYS FROM ROUTE: %#", [dic allKeys]);
legs = [dic objectForKey:#"legs"];
// NSLog(#"legs array count %d", legs.count);
for(int i = 0; i < legs.count; i++){
stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
NSLog(#"############################");
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
}
}
}
}
});
first you go to your .h file -->
#property (nonatomic, strong) NSMutableArray * detailsArray;
In .m file -->
#synthesize detailsArray;
replace this code
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
by this -->
self.detailsArray = [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"];
# using table datasource methods
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [self.detailsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.titleLabel.text = [self.detailsArray objectAtIndex: indexPath.row ];
return cell;
}
}
//Note Please set the delegate method of table , if you write the code programmatically means tableView.delgate = self;
Use this :
self.detaisArray = [[NSMutableArray alloc] init];
// Do any additional setup after loading the view, typically from a nib.
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",startPoint,midannotation.coordinate.latitude,midannotation.coordinate.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSString *someString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// NSLog(#"data:%#",someString);
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
NSArray *arr = [parsedJson objectForKey:#"routes"];
NSDictionary *dic = [arr objectAtIndex:0];
// NSLog(#"ALL KEYS FROM ROUTE: %#", [dic allKeys]);
NSArray *legs = [dic objectForKey:#"legs"];
// NSLog(#"legs array count %d", legs.count);
for(int i = 0; i < legs.count; i++){
NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
NSLog(#"############################");
[self.detaisArray addObject:[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ];
if(i == legs.count-1){
self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 400) style:UITableViewStylePlain];
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
[self.view addSubview:self.myTableView];
}
}
}
}
}
});
first checked you connect your tableview delegate set self...
second checked youn row count pr detailarray cont in numberOfRowsInSection its may b zero
1st Declare Your Array in .h
like this
#property(strong,nonatomic)NSMutableArray * name;
And intialize into .m Init() method
name=[NSMutableArray alloc]initWithObjects:#"a",#"b", nil];
// TableView Delegate Method To Display Array Data into Tableview.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return name.count; //Give Your Array Name Here.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[NSString stringWithFormat:#"%#",[name objectAtIndex:indexPath.row]];
return cell;
}
Try this code.

How to keep the checkmark in a UITableView after the view disappears

I have a uitableview that's displaying multiple selections with a custom checkmark. When selected the rows value is save using NSUserDefaults. The problem is that despite the values being saved the checkmarks disappear from the table cell rows. I can't figure out why.
thanks for any help, I'm really stuck on this.
Here's the .h code:
#interface CategoriesViewController : UITableViewController {
NSString *selectedCategoryTableString;
NSString *jsonStringCategory;
int prev;
}
// arForTable array will hold the JSON results from the api
#property (nonatomic, retain) NSArray *arForTable;
#property (nonatomic, retain) NSMutableArray *arForIPs;
#property (nonatomic, retain) NSMutableArray *categorySelected;
#property (nonatomic, retain) NSString *jsonStringCategory;
#property(nonatomic, retain) UIView *accessoryView;
#end
and the .m code:
#implementation CategoriesViewController
#synthesize jsonStringCategory;
#synthesize arForTable = _arForTable;
#synthesize arForIPs = _arForIPs;
- (void)viewDidLoad
{
[super viewDidLoad];
self.arForIPs=[NSMutableArray array];
self.categorySelected = [[NSMutableArray alloc] init];
[self reloadMain];
self.tableView.allowsMultipleSelection = YES;
}
-(void) reloadMain {
jsonString = #"http:///******";
// Download the JSON
NSString *jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:jsonString]
encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
NSMutableArray *itemsTMP = [[NSMutableArray alloc] init];
// Create parser
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
itemsTMP = [results objectForKey:#"results"];
self.arForTable = [itemsTMP copy];
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.arForTable count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell.textLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
[cell.detailTextLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
cell.accessoryView.hidden = NO;
}
UIImageView *cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon-tick.png"]] ;
UIImageView *cellAccessoryNoneImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#""]] ;
if([self.arForIPs containsObject:indexPath]){
cell.accessoryView = cellAccessoryImageView;
} else {
cell.accessoryView = cellAccessoryNoneImageView;
}
// Get item from tableData
NSDictionary *item = (NSDictionary *)[_arForTable objectAtIndex:indexPath.row];
// encoding fix
NSString *utf8StringTitle = [item objectForKey:#"name"];
NSString *correctStringTitle = [NSString stringWithCString:[utf8StringTitle cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];
cell.textLabel.text = [correctStringTitle capitalizedString];
NSNumber *num = [item objectForKey:#"id"];
cell.detailTextLabel.text = [num stringValue];
cell.detailTextLabel.hidden = YES;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if([self.arForIPs containsObject:indexPath]){
[self.arForIPs removeObject:indexPath];
[self.categorySelected removeObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:#"id"]];
} else {
[self.arForIPs addObject:indexPath];
[self.categorySelected addObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:#"id"]];
NSLog(#"%# categorySelected",self.categorySelected);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSLog(#"%# defaults categorySelected",[defaults arrayForKey:#"selectedCategoryTableString"]);
NSString *string = [self.categorySelected componentsJoinedByString:#","];
[defaults setObject:string forKey:#"selectedCategoryTableString"];
NSLog(#"%# STRING",string);
}
[tableView reloadData];
}
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:NO];
[self.navigationController setNavigationBarHidden:YES animated:NO];
self.navigationController.toolbarHidden = YES;
}
First of all your code has lots of memory leaks, please do use the static analyzer and/or instruments to fix them, few for them are pretty obvious like you initialized the SBJSON parser and did not release it, itemsTMP is another.
I have rewritten your code to be much more efficient and memory friendly:
#interface CategoriesViewController : UITableViewController
{
NSArray *_items;
NSMutableArray *_selectedItems;
UIImageView *cellAccessoryImageView;
}
#end
#implementation CategoriesViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_selectedItems = [NSMutableArray new];
cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon-tick.png"]] ;
[self reloadMain];
self.tableView.allowsMultipleSelection = YES;
}
- (void)reloadMain
{
NSString *jsonString = #"http:///******";
// Download the JSON
jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:jsonString]
encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
// Create parser
SBJSON *parser = [SBJSON new];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
if (_items) [_items release];
_items = [[results objectForKey:#"results"] copy];
[parser release];
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
[cell.textLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
[cell.detailTextLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
cell.accessoryView.hidden = NO;
}
NSDictionary *item = [_items objectAtIndex:indexPath.row];
if ([_selectedItems containsObject:item])
{
// preloaded image will help you have smoother scrolling
cell.accessoryView = cellAccessoryImageView;
}
else
{
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryNone;
}
// Get item from tableData
cell.textLabel.text = [[NSString stringWithCString:[[item objectForKey:#"name"] cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding] capitalizedString];
cell.detailTextLabel.text = [[item objectForKey:#"id"] stringValue];
cell.detailTextLabel.hidden = YES;
item = nil;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *item = [_items objectAtIndex:indexPath.row];
if ([_selectedItems containsObject:item])
{
[_selectedItems removeObject:item];
}
else
{
[_selectedItems addObject:item];
}
item = nil;
[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (void)dealloc
{
[_selectedItems release];
[cellAccessoryImageView release];
[super dealloc];
}
#end
Since in your table there is only one section. Try this approach and this will help you certainly.
In - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath write following code;
if([self.arForIPs containsObject:[NSNumber numberWithInt:indexPath.row]]){
cell.accessoryView = cellAccessoryImageView;
} else {
cell.accessoryView = cellAccessoryNoneImageView;
}
And in - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath write code as below,
if([self.arForIPs containsObject:[NSNumber numberWithInt:indexPath.row]]){
[self.arForIPs removeObject:[NSNumber numberWithInt:indexPath.row]];
} else {
[self.arForIPs addObject:[NSNumber numberWithInt:indexPath.row]]
}

Problem to put data in UITableView

i write this code
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
dataToDisplay = [[NSMutableArray alloc] init];
//NSString *myJSON = [[NSString alloc] initWithString:responseString];
NSDictionary *json = [responseString JSONValue];
Status *statut = [[Status alloc] init];
statut.flyNumber = [json objectForKey:#"flynumber"];
statut.ftatuts = [json objectForKey:#"fstatuts"];
statut.escDepart = [json objectForKey:#"escdepart"];
statut.escArrival = [json objectForKey:#"escarrival"];
statut.proArrival = [json objectForKey:#"proarrival"];
statut.proDepart = [json objectForKey:#"prodepart"];
statut.estDepart = [json objectForKey:#"estdepart"];
statut.estArrival = [json objectForKey:#"estarrival"];
statut.realDepart = [json objectForKey:#"realdepart"];
statut.realArrival = [json objectForKey:#"realarrived"];
[dataToDisplay addObject:statut];
NSLog(#"ok");
}
- (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 [dataToDisplay count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
NSLog(#"1 ok");
Status *statut2 = [dataToDisplay objectAtIndex:indexPath.row];
NSLog(#"2 ok");
cell.textLabel.text = [NSString stringWithFormat:#"%# - %#",statut2.flyNumber,statut2.ftatuts];
NSLog(#"3 ok");
return cell;
}
The problem that the table still empty . And i don't have "ok 1" message in the console .
This is my controller .h
#import <UIKit/UIKit.h>
#import "ASIHTTPRequest.h"
#import "JSON.h"
#import "Status.h"
#interface StatusTableViewController : UITableViewController {
NSString * Flynumber;
NSMutableArray *dataToDisplay;
}
#property(retain,nonatomic) IBOutlet NSString * Flynumber;
#end
i added [self.tableView reloadData]; and it work .
But how to put each result on a line (cell) ?
To execute a reload you have to execute :
[self.tableView reloadData];
at the end of the requestFinished: function
provided you have set everything else correctly, would you try and execute a reloadData at the end of - (void)requestFinished:(ASIHTTPRequest *)request?
Does your controller (?) conform to the UITableViewDelegate and UITableViewDataSource protocols?
#interface YourController : UIViewController <UITableViewDelegate, UITableViewDataSource> {...}
If yes, check to make sure you've set the dataSource property. Typically, this is set to self.

Turning additional strings in this JSON array into a UITableView Detail

I have a NSURL request that brings back an array of "name" and "phone", "etc"... The "name" Key shows up fine on the master table, but I'm having trouble figuring out how to get the rest of the array to show up on the detail table when I select the row. (I have the DetailerTableViewController working to accept the view). Any help would be appreciated.
Thanks,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [rowsArray count];
NSLog(#"row count: %#",[rowsArray count]);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *dict = [rowsArray objectAtIndex: indexPath.row];
cell.textLabel.text = [dict objectForKey:#"name"];
cell.detailTextLabel.text = [dict objectForKey:#"loginName"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.0/255.0 green:207.0/255.0 blue:255.0/255.0 alpha:1.0];
self.title = NSLocalizedString(#"Master", #"Master");
NSURL *url = [NSURL URLWithString:#"http://10.0.1.8/~imac/iphone/jsontest.php"];
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url];
NSLog(jsonreturn); // Look at the console and you can see what the results are
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
// In "real" code you should surround this with try and catch
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict)
{
rowsArray = [dict objectForKey:#"member"];
[rowsArray retain];
}
NSLog(#"Array: %#",rowsArray);
NSLog(#"count is: %i", [self.rowsArray count]);
[jsonreturn release];
}
You need to implement:
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
to handle row selection and to push the view controller for the detail view.