(Terminating app due to uncaught exception 'NSInvalidArgumentException) - iphone

I am using uitableview for showing the json parsed data . the parsed data is stored in array and the array list is 100 asigned to uitableview. but it crashing at objectAtIndex
at {forloop} it showing crash report as
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: ' -[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 0'*
plese help me
- (void)viewDidLoad
{
self.responseData = [NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:openexchangeURl]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[super viewDidLoad];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
self.responseData = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
values = [responseString JSONValue];
array = [[NSMutableArray alloc] init];
NSMutableArray *arrTitle = [[NSMutableArray alloc] init];
NSMutableArray *arrValues = [[NSMutableArray alloc] init];
array =[values valueForKey:#"rates"];
NSLog(#"array values:--> %#",array);
// NSLog(#"values:--> %#",values);
// NSLog(#"Particular values:--> %#",[[values valueForKey:#"rates"] valueForKey:#"AED"]);
tempDict1 = (NSMutableDictionary *)array;
NSArray *arr;// =[[NSArray alloc]init];
arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
NSLog(#"arr-->%#",arr);
NSString *subStar = #"=";
[arrTitle removeAllObjects];
[arrValues removeAllObjects];
for (int i=0; i<[arr count]-1; i++)
{
[arrTitle addObject:[[arr objectAtIndex:i] substringToIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])-1]];
[arrValues addObject:[[arr objectAtIndex:i] substringFromIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])]];
NSLog(#"arrTitle is:--> %#",arrTitle);
}
tempDict1 = (NSMutableDictionary*)[array objectAtIndex:0];
array = [values valueForKey:#"rates"];
NSLog(#"tempDict--%#",[tempDict1 objectForKey:#"AED"]);
[array retain];
[tbl_withData reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"array-->%#",array);
return [array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
intIndexPath = indexPath.row;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.font = [UIFont systemFontOfSize:8];
cell.textLabel.numberOfLines = 4;
}
// NSLog(#"data is like:--> %#",array);
// cell.textLabel.text= [NSString stringWithFormat:#"%#",[array objectAtIndex:intIndexPath]];
cell.textLabel.text =[array objectAtIndex:intIndexPath];
return cell;
}

There is only one item in your array, here is where you add just the one object:
array = [[NSMutableArray alloc] init];
[array addObject:[values valueForKey:#"rates"]];
You should assign the the value that you get from the [values valueForKey:#"rates"] to the array variable. Also make the array variable a property that will retain the value.
#property (nonatomic, strong) NSArray *array;
then assign it to the property:
self.array = [values valueForKey:#"rates"];
Also move all styling of the cell to the if where you create the new cell. This will speed thing up, since you not change the style of the cell every time.
- (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.adjustsFontSizeToFitWidth = YES;
cell.textLabel.font = [UIFont systemFontOfSize:8];
cell.textLabel.numberOfLines = 4;
}
NSLog(#"data is like:--> %#",array);
// NSString *cellValue =[array objectAtIndex:indexPath.row];
// cell.textLabel.text = cellValue;
cell.textLabel.text= [NSString stringWithFormat:#"%#",[array objectAtIndex:indexPath.row]];
return cell;
}

Get your data from server in correct format...in your situation your data is in one array. so make it in different different array..
{"reply":["AED = 3.673188","AFN = 48.5725","","","",""]}
or you can parse your response and save single single data into another array...

Related

getting data in connectionDidFinishLoading,but ubable to use those data in cellForRowAtIndexPath method

I am developing an iphone application. In this i have to generate user profile form dynamically according to field information coming from the server.
So, if there are 5 fields in response i want ton create 5 labels from those data to display in cell of uitableview.
Not that i am getting the name of fields for user profile, not the values of profile.
I want to generate form dynamically from those data.
I'm able to get those data in NSMutableArray but in cellForRowAtIndexPath method its showing null.
How can i solve this?
My code snippet is as follow.
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
if (connection)
{
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//You've got all the data now
//Do something with your response string
// NSLog(#"Response:%#",responseString);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *object = [parser objectWithString:responseString error:nil];
NSString *pec_count = [object valueForKey:#"peculiarity_count"];
NSDictionary *pecs = [object valueForKey:#"peculiarities"];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:nil];
[array addObject:#""];
for (int j= 1; j <= [pec_count integerValue] ; j++) {
NSString *val = [NSString stringWithFormat:#"%#%d",#"pec_",j];
NSString *pec_i = [pecs valueForKey:val];
NSString *modifiedString = [pec_i stringByReplacingOccurrencesOfString:#"_" withString:#" "];
NSString *capitalisedSentence = [modifiedString stringByReplacingCharactersInRange:NSMakeRange(0,1)
withString:[[modifiedString substringToIndex:1] capitalizedString]];
[array insertObject:capitalisedSentence atIndex:j];
}
self.peculiarity = array;
[self.table reloadData];
}
for (int j=0 ; j < [self.peculiarity count] ; j++) {
NSLog(#"info:%#", [self.peculiarity objectAtIndex: j]);
}
}
- (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];
UIButton *racebtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
racebtn.frame = CGRectMake(240, 7, 10, 15);
[racebtn setBackgroundImage:[UIImage imageNamed:#"select.png"] forState:UIControlStateNormal];
[racebtn addTarget:self action:#selector(selectRace:)forControlEvents:UIControlEventTouchUpInside];
NSLog(#"cell=%#",[self.peculiarity objectAtIndex:3]);
}
Any help will be appreciated.
Thank you.
in connectionDidFinishLoading: method replace the following line:
self.peculiarity = array; with,
self.peculiarity = [[NSMutableArray alloc] initWithArray:array];
and in cellForRowAtIndexPath method add the following line of code:
cell.textLabel.text = [self.peculiarity objectAtIndex:indexPath.row];
hope this will help you.
Note: If you did not allocated self.peculiarity NSMutableArray then alloc that array like bellow..
if (self.peculiarity == nil)
self.peculiarity = [[NSMutableArray alloc] init];
and then assign that array to this array like bellow..
self.peculiarity = array;
after in cellForRowAtIndexPath: method just set that value or name to the textLabel Of the UITableViewCell like bellow..
cell.textLabel.text = [self.peculiarity objectAtIndex:indexPath.row];
see whole example with that method..
- (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];
UIButton *racebtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
racebtn.frame = CGRectMake(240, 7, 10, 15);
[racebtn setBackgroundImage:[UIImage imageNamed:#"select.png"] forState:UIControlStateNormal];
[racebtn addTarget:self action:#selector(selectRace:)forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:racebtn];
cell.textLabel.text = [self.peculiarity objectAtIndex:indexPath.row];
}
return cell;
}
I already have checked all above solutions before, Then finally i got solution for this. The problem was that my cell was getting loaded before arrival of data. So i used synchronous request to the server.
Code is below for this :
NSString *path = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"path"];
NSString *address = [NSString stringWithFormat:#"%#%#%#%#", path,#"users/",#"peculiarity/",self.tablename];
NSURL *URL = [NSURL URLWithString:address];
NSLog(#"%#",address);
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[URL host]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
timeoutInterval:60.0];
[request setHTTPMethod:#"GET"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (data) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data:%#",responseString);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *object = [parser objectWithString:responseString error:nil];
pecs = [object valueForKey:#"pec_values"];
for (int j =0; j < [pecs count] ; j++) {
NSLog(#"values:%#",[pecs objectAtIndex:j]);
}
self.peculiarity = array;
}
else {
// Handle error by looking at response and/or error values
NSLog(#"%#",error);
}

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.

Second view in UITableView will not display parsed data from JSON

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...

array returns null value ,arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];

I am having a problem with displaying NSArray values in a UITableView. In my code I am getting nil value.
arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
values = [responseString JSONValue];
array = [[NSMutableArray alloc] init];
NSMutableArray *arrTitle = [[NSMutableArray alloc] init];
NSMutableArray *arrValues = [[NSMutableArray alloc] init];
array =[values valueForKey:#"rates"];
NSLog(#"array values:--> %#",array);
// NSLog(#"values:--> %#",values);
// NSLog(#"Particular values:--> %#",[[values valueForKey:#"rates"] valueForKey:#"AED"]);
tempDict1 = (NSMutableDictionary *)array;
NSArray *arr;// =[[NSArray alloc]init];
arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
NSLog(#"arr-->%#",arr);
NSString *subStar = #"=";
[arrTitle removeAllObjects];
[arrValues removeAllObjects];
for (int i=0; i<[arr count]-1; i++)
{
[arrTitle addObject:[[arr objectAtIndex:i] substringToIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])-1]];
[arrValues addObject:[[arr objectAtIndex:i] substringFromIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])]];
NSLog(#"arrTitle is:--> %#",arrTitle);
}
tempDict1 = (NSMutableDictionary*)[array objectAtIndex:0];
array = [values valueForKey:#"rates"];
NSLog(#"tempDict--%#",[tempDict1 objectForKey:#"AED"]);
[array retain];
[tbl_withData reloadData];
}
uitableview code is below
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"array-->%#",array);
return [array count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
intIndexPath = indexPath.row;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.font = [UIFont systemFontOfSize:8];
cell.textLabel.numberOfLines = 4;
}
// NSLog(#"data is like:--> %#",array);
// cell.textLabel.text= [NSString stringWithFormat:#"%#",[array objectAtIndex:intIndexPath]];
cell.textLabel.text =[array objectAtIndex:intIndexPath];
return cell;
}
Look through table view programming guide
https://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/AboutTableViewsiPhone/AboutTableViewsiPhone.html
You have to implement UITableView delegate methods in your class to fill table view with content.
Also see this:
https://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/CreateConfigureTableView/CreateConfigureTableView.html#//apple_ref/doc/uid/TP40007451-CH6-SW10
Here is code:
//this is your dictionary:
self.values = [[[NSMutableDictionary alloc] init] autorelease];
//filled it with values:
[self.values setObject:#"201" forKey:#"ams"];
[self.values setObject:#"500.50" forKey:#"hyd"];
[self.values setObject:#"200.10" forKey:#"guj"];
[self.values setObject:#"400" forKey:#"afgd"];
//now get an array of keys out of it. Can do it anywehe... For example in connectionDidFinishLoading method
self.keys = [[[NSArray alloc] initWithArray:[values allKeys]] autorelease];
Now cellForRoAtIndexPath method:
- (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.adjustsFontSizeToFitWidth = YES;
cell.textLabel.font = [UIFont systemFontOfSize:8];
cell.textLabel.numberOfLines = 4;
}
NSString *currentKey = [self.keys objectAtIndex:indexPath.row];
NSString *currentValue = [self.values objectForKey:currentKey];
NSString *cellText = [NSString stringWithFormat:#"%#:%#", currentKey, currentValue];
cell.textLabel.text = cellText;
return cell;
}
It worked on my machine..

how to assign a static row at the first and last row of dynamically allocated data in table view

i m parsing a json file and populating it in my table view what i want to assign is a static row.at the first and last row of my tableview named as Var tycker du. but doing so.it overlaps the dynamically allocated data from json file..could you guys help me out below is the code.
static NSString * const kCellTextKey = #"CellTextKey";
static NSString * const kCellStateKey = #"CellStateKey";
static NSString* kAppId = #"126013844184727";
#define KFBAccessToken #"126013844184727"
#define KFBExpirationDate #"KFBExpirationDate"
#implementation Tab5
#synthesize tableview1,jsonData,jsonArray,story,media1,url,descriptiondesc,media2;
#synthesize arForIPs = _arForIPs;
- (void)viewDidLoad {
[super viewDidLoad];
objMan = [[HJObjManager alloc] initWithLoadingBufferSize:6 memCacheSize:20];
self.arForIPs=[NSMutableArray array];
self.tableview1.backgroundColor=[UIColor clearColor];
[self.tableview1 setAllowsSelectionDuringEditing:TRUE];
jsonurl=[NSURL URLWithString:#"http://dev-parkguiden.knutpunkten.se/Api/GetPark? parkid=3"];
NSURLRequest *request = [NSURLRequest requestWithURL:jsonurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
connection1=[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
self.jsonData=[NSData dataWithContentsOfURL:jsonurl];
NSDictionary *items=[NSJSONSerialization JSONObjectWithData:self.jsonData options:NSJSONReadingMutableLeaves error:nil];
items1 = [items objectForKey:#"ThingsTodo"];
story = [[NSMutableArray array]retain];
media1 = [[NSMutableArray array]retain];
url=[[NSMutableArray array]retain];
media2=[[NSMutableArray array]retain];
descriptiondesc=[[NSMutableArray array]retain];
dog=[[NSMutableArray array]retain];
arr=[[NSMutableArray array]retain];
bose=[[NSMutableArray array]retain];
for (NSDictionary *item in items1)
{
[self.story addObject:[item objectForKey:#"Name"]];
[self.media1 addObject:[item objectForKey:#"Status"]];
//[self.media2 addObject:[item objectForKey:#"Image"]];
}
//NSLog(#"room:%#",items1);
[self makeNewArray];
}
-(void)makeNewArray
{
for ( int i=0; i<[self.media1 count]; i++)
{
NSDictionary *boy=[self.media1 objectAtIndex:i];
NSString *str=[[NSString alloc]initWithFormat:#"%#",boy];
//NSLog(#"the value:%#",str);
if([str isEqualToString:#"1"])
{
text = [self.story objectAtIndex:i];
NSString *text1 = [NSString stringWithFormat:#"%#",text];
NSNumber *state = [NSNumber numberWithBool:NO];
dict=[NSDictionary dictionaryWithObjectsAndKeys:text1,kCellTextKey,state,kCellStateKey,nil];
[arr addObject:dict];
// [dog addObject:[self.story objectAtIndex:i]];
}
dog=[arr mutableCopy];
NSLog(#"wat hav i got:%#",arr);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dog 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.text=[dog objectAtIndex:indexPath.row];
NSDictionary *rowData = [dog objectAtIndex:indexPath.row];
cell.textLabel.text = [rowData objectForKey:kCellTextKey];
if ([[rowData objectForKey:kCellStateKey] boolValue]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
[bose removeObject:[newDict valueForKey:#"CellTextKey"]];
// NSLog(#"object going to get removed:%#",bose);
}
sectionRows = [tableview1 numberOfRowsInSection:[indexPath section]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dict = [dog objectAtIndex:indexPath.row];
BOOL newState = ![[dict objectForKey:kCellStateKey] boolValue];
newDict = [NSDictionary dictionaryWithObjectsAndKeys:[dict objectForKey:kCellTextKey], kCellTextKey, [NSNumber numberWithBool:newState], kCellStateKey, nil];
[dog replaceObjectAtIndex:indexPath.row withObject:newDict];
[bose addObject:[newDict valueForKey:#"CellTextKey"]];
NSLog(#"the current added data:%#",bose);
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
}
hey try out with this solution
-(void)makeNewArray
{
for ( int i=0; i<[self.media1 count]; i++)
{
NSDictionary *boy=[self.media1 objectAtIndex:i];
NSString *str=[[NSString alloc]initWithFormat:#"%#",boy];
//NSLog(#"the value:%#",str);
if([str isEqualToString:#"1"])
{
text = [self.story objectAtIndex:i];
NSString *text1 = [NSString stringWithFormat:#"%#",text];
NSNumber *state = [NSNumber numberWithBool:NO];
dict=[NSDictionary dictionaryWithObjectsAndKeys:text1,kCellTextKey,state,kCellStateKey,nil];
[arr addObject:dict];
// [dog addObject:[self.story objectAtIndex:i]];
}
}
NSDictionary *dict;
dict = [NSDictionary dictionaryWithObjectsAndKeys:
#"Var tycker du", #"CellTextKey",
#"0", #"CellStateKey", nil];
[dog addObject:dict];
for(int i=0; i<arr.count; i++){
[dog addObject:[arr objectAtIndex:i]];
}
[dog addObject:dict];
// dog=[arr mutableCopy];
NSLog(#"wat hav i got:%#",dog);
}