i am getting data from service which i successfully parse like this
-(NSMutableArray *)clubTypes
{
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSString *url = [NSString stringWithFormat:#"%#category",KWSURLList];
NSLog(#"%#",url);
NSDictionary * returnDict = (NSDictionary *) [self callWebService:url];
if([returnDict objectForKey:#"result"])
{
// NSDictionary * returnDictResult = (NSDictionary *) [returnDict objectForKey:#"result"];
NSArray *returnedArray = [returnDict objectForKey:#"data"];
for(NSDictionary *clubDict in returnedArray)
{
ClubTypeDC *clubDC = [[ClubTypeDC alloc] init];
clubDC.clubTypeID = [[clubDict objectForKey:#"Id"] intValue];
clubDC.clubTypeTitle = [clubDict objectForKey:#"tittle"];
clubDC.clubTypeImage = [clubDict objectForKey:#"icons"];
[dataArray addObject:clubDC];
// NSLog(#"%#",proEvents.proEventImage);
}
}
}
but i always get an error bad access in numberOfRowsInSection. can any one tell me why?
Remember always return your array like this
return dataArray;
i edited your code, please check it
-(NSMutableArray *)clubTypes
{
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSString *url = [NSString stringWithFormat:#"%#category",KWSURLList];
NSLog(#"%#",url);
NSDictionary * returnDict = (NSDictionary *) [self callWebService:url];
if([returnDict objectForKey:#"result"])
{
// NSDictionary * returnDictResult = (NSDictionary *) [returnDict objectForKey:#"result"];
NSArray *returnedArray = [returnDict objectForKey:#"data"];
for(NSDictionary *clubDict in returnedArray)
{
ClubTypeDC *clubDC = [[ClubTypeDC alloc] init];
clubDC.clubTypeID = [[clubDict objectForKey:#"Id"] intValue];
clubDC.clubTypeTitle = [clubDict objectForKey:#"tittle"];
clubDC.clubTypeImage = [clubDict objectForKey:#"icons"];
[dataArray addObject:clubDC];
// NSLog(#"%#",proEvents.proEventImage);
}
}
return dataArray;
}
return dataArray
in your function at last
and
use this in numberOfRowsInSection...
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([dataArray count] > 0) {
return dataArray.count;
}
else {
return 0;
}
}
Related
I want to use multiple sections feature UITableView. I have a single NSMutableArray which consists of data in dictionary format. In that dictionary there is a key which has values as '0' and '1'.
I want to create two separate NSMutableArray out of that so that I can assign them accordingly in different sections.
For example :
if (indexPath.section==0) {
NSDictionary *Data = [roomList1 objectAtIndex:indexPath.row];
} else {
NSDictionary *Data = [roomList2 objectAtIndex:indexPath.row];
}
Assuming the value in your dictionary is always set you could do something like:
NSMutableArray *firstArray = [NSMutableArray new];
NSMutableArray *secondArray = [NSMutableArray new];
for (NSDictionary *dictionary in yourArray) {
if ([dictionary objectForKey:#"yourValue"] isEqualToString: #"0") {
[firstArray addObject:dictionary];
} else if ([dictionary objectForKey:#"yourValue"]isEqualToString: #"1") {
[secondArray addObject:dictionary];
}
}
You can use this
- (NSDictionary *)groupObjectsInArray:(NSArray *)array byKey:(id <NSCopying> (^)(id item))keyForItemBlock
{
NSMutableDictionary *groupedItems = [NSMutableDictionary new];
for (id item in array) {
id <NSCopying> key = keyForItemBlock(item);
NSParameterAssert(key);
NSMutableArray *arrayForKey = groupedItems[key];
if (arrayForKey == nil) {
arrayForKey = [NSMutableArray new];
groupedItems[key] = arrayForKey;
}
[arrayForKey addObject:item];
}
return groupedItems;
}
Ref: Split NSArray into sub-arrays based on NSDictionary key values
Use like this
NSMutableArray * roomList1 = [[NSMutableArray alloc] init];
NSMutableArray * roomList2 = [[NSMutableArray alloc] init];
for(int i = 0;i< YourWholeArray.count;i++)
{
if([[[YourWholeArray objectAtIndex:i] valueForKey:#"YourKeyValueFor0or1"] isEqualToString "0"])
{
[roomList1 addObject:[YourWholeArray objectAtIndex:i]];
}
else if([[YourWholeArray objectAtIndex:i] valueForKey:#"YourKeyValueFor0or1"] isEqualToString "1"])
{
[roomList2 addObject:[YourWholeArray objectAtIndex:i]];
}
}
NSMutableArray *roomList1 = [[NSMutableArray alloc] init];
NSMutableArray *roomList2 = [[NSMutableArray alloc] init];
for (NSString *key in [myDictionary allKeys]) {
if (myDictionary[key] isEqualToString: #"0") {
[roomList1 addObject: myDictionary[key]];
} else {
[roomList2 addObject: myDictionary[key]];
}
}
try this way :-
NSMutableArray *getdata=[[NSMutableArray alloc]init];
getdata=[results objectForKey:#"0"];
NSMutableArray *getdata2=[[NSMutableArray alloc]init];
getdata2=[results objectForKey:#"1"];
use this two array and populate the section with now of rows at indexpathrow
define number of section 2
if (section==0){
getdata
}
else{
getdata2
}
I am using UISegmentedControl and using UITableView but my query is segment button 1 click and display data for yes and 2 button click and display data from no and adding A to Z section UITableView first button click properly data display and properly tableview section atoz display but 2 button click and app crash `
#import "ZnameViewController.h"
#import "ZpaleoViewController.h"
#import "SWRevealViewController.h"
#interface ZnameViewController ()
#end
#implementation ZnameViewController
#synthesize strname1,sagmentController,objtbl,name;
- (void)viewDidLoad {
[super viewDidLoad];
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.slide setTarget: self.revealViewController];
[self.slide setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
databse = [FMDatabase databaseWithPath:appdelegate.appDBPath];
[arrCatname removeAllObjects];
[arrPaleo removeAllObjects];
arrCatname = [[NSMutableArray alloc]init];
arrPaleo = [[NSMutableArray alloc]init];
arrStatus = [[NSMutableArray alloc]init];
arrCat2 = [[NSMutableArray alloc]init];
arrSta2 = [[NSMutableArray alloc]init];
[self segmentSwitch:self];
// Do any additional setup after loading the view.
}
- (IBAction)segmentSwitch:(id)sender {
[databse open];
NSString *selectQuery = [NSString stringWithFormat:#"select * from Food ORDER BY name ASC"];
NSLog(#"%#",selectQuery);
FMResultSet *resultQuary = [databse executeQuery:selectQuery];
while ([resultQuary next]) {
// NSString *z_paleo = [resultQuary stringForColumn:#"status"];
z_paleo = [NSString stringWithFormat:#"%d",[resultQuary intForColumn:#"status"]];
if ([z_paleo isEqualToString:#"1"]) {
if(z_name == nil || [z_name isKindOfClass:[NSNull null]])
{
[arrPaleo addObject:#""];
}
else{
[arrPaleo addObject:z_name];
}
[arrSta2 addObject:z_paleo];
}
else{
if(z_name == nil || [z_name isKindOfClass:[NSNull null]])
{
[arrCatname addObject:#""];
}
else
{
[arrCatname addObject:z_name];
}
[arrCat2 addObject:z_paleo];
}
}
[databse close];
if(sagmentController.selectedSegmentIndex == 0)
{
if ([z_paleo isEqualToString:#"1"]) {
[self getName:arrPaleo];
objtbl.hidden = NO;
}
}
else if (sagmentController.selectedSegmentIndex == 1)
{
if ([z_paleo isEqualToString:#"0"]) {
[self getName:arrCatname];
objtbl.hidden = NO;
}
}
[objtbl reloadData];
}
-(void)getName:(NSMutableArray *)arr
{
NSMutableArray *temp = [[NSMutableArray alloc] init];
NSMutableArray *temp2 = [[NSMutableArray alloc] init];
for(int i = 0; i < arr.count; i++)
{
NSString *string = [arr objectAtIndex:i];
dict = [[NSMutableDictionary alloc] init];
[dict setObject:string forKey:#"Name"];
[dict setObject:[NSNumber numberWithInt:i] forKey:#"ID"];
NSString *firstString = [string substringToIndex:1];
if([temp2 containsObject:firstString] == NO || temp2.count == 0)
{
if(temp2.count != 0)
{
[temp addObject:temp2];
temp2 = [[NSMutableArray alloc] init];
}
[temp2 addObject:firstString];
}
[temp2 addObject:dict];
}
[temp addObject:temp2];
sorted = [[NSArray alloc] initWithArray:temp];
}
-(void)getname2:(NSMutableArray *)array{
NSMutableArray *temp = [[NSMutableArray alloc] init];
NSMutableArray *temp2 = [[NSMutableArray alloc] init];
for(int i = 0; i < array.count; i++)
{
NSString *string = [array objectAtIndex:i];
dict1 = [[NSMutableDictionary alloc] init];
[dict1 setObject:string forKey:#"Name"];
[dict1 setObject:[NSNumber numberWithInt:i] forKey:#"ID"];
NSString *firstString = [string substringToIndex:1];
if([temp2 containsObject:firstString] == NO || temp2.count == 0)
{
if(temp2.count != 0)
{
[temp addObject:temp2];
temp2 = [[NSMutableArray alloc] init];
}
[temp2 addObject:firstString];
}
[temp2 addObject:dict1];
}
[temp addObject:temp2];
sorted1 = [[NSArray alloc] initWithArray:temp];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
int i = 0;
for(NSArray *array in sorted)
{
NSString *string = [array objectAtIndex:0];
if([string compare:title] == NSOrderedSame)
break;
i++;
}
return i;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (sagmentController.selectedSegmentIndex == 0) {
return [sorted count];
}else {
return [sorted count];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *array = [sorted objectAtIndex:section];
return [array objectAtIndex:0];
//return [foodIndexTitles objectAtIndex:section];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
NSMutableArray *titleArray = [NSMutableArray array];
[titleArray addObject:#"A"];
[titleArray addObject:#"B"];
[titleArray addObject:#"C"];
[titleArray addObject:#"D"];
[titleArray addObject:#"E"];
[titleArray addObject:#"F"];
[titleArray addObject:#"G"];
[titleArray addObject:#"H"];
[titleArray addObject:#"I"];
[titleArray addObject:#"J"];
[titleArray addObject:#"K"];
[titleArray addObject:#"L"];
[titleArray addObject:#"M"];
[titleArray addObject:#"N"];
[titleArray addObject:#"O"];
[titleArray addObject:#"P"];
[titleArray addObject:#"Q"];
[titleArray addObject:#"R"];
[titleArray addObject:#"S"];
[titleArray addObject:#"T"];
[titleArray addObject:#"U"];
[titleArray addObject:#"V"];
[titleArray addObject:#"W"];
[titleArray addObject:#"X"];
[titleArray addObject:#"Y"];
[titleArray addObject:#"Z"];
return titleArray;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (sagmentController.selectedSegmentIndex == 1) {
NSArray *array = [sorted objectAtIndex:section];
return (array.count - 1);
}else{
NSArray *array = [sorted objectAtIndex:section];
return (array.count - 1);
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifire = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifire];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifire];
}
if (sagmentController.selectedSegmentIndex == 0) {
NSArray *array = [sorted objectAtIndex:indexPath.section];
dict = [array objectAtIndex:indexPath.row + 1];
cell.textLabel.text = [dict objectForKey:#"Name"];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Yes_check.png"]];
[cell.accessoryView setFrame:CGRectMake(0, 0, 15, 15)];
}
else
{
NSArray *array = [sorted objectAtIndex:indexPath.section];
dict = [array objectAtIndex:indexPath.row + 1];
cell.textLabel.text = [dict objectForKey:#"Name"];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"No.png"]];
[cell.accessoryView setFrame:CGRectMake(0, 0, 15, 15)];
return cell;
}
return cell;
}
I am trying to figure out how I can get data from a JSON array that is in another array.
Here is the JSON. I'm wanting to get one of the image URLs from photos.
[
{
"id":6901439,
"name":"INDTTIN CD",
"description":"Full-length released June 2013 via Little Heart Records. \r\n\r\nTrack Listing:\r\n\r\n1. Tired\r\n2. Time to Heal\r\n3. Gypsy Summer\r\n4. Sketchbooks\r\n5. I Never Deserve the Things I Need\r\n6. Say it With the \"I\"\r\n7. A Negative Mind\r\n8. Rafters\r\n9. Indrid Cold\r\n10. Present Tense ",
"short_url":"http://onmyhonor.storenvy.com/products/6901439-indttin-cd",
"status":"active",
"labels":null,
"preorder":false,
"on_sale":true,
"store_id":373949,
"price":"7.00",
"marketplace_category":"music-cds",
"marketplace_category_id":345,
"photos":[
{
"photo":{
"original":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_original.jpg",
"large":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_large.jpg",
"homepage":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_homepage.jpg",
"medium":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_medium.jpg",
"small":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_small.jpg",
"64w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_64w.jpg",
"200w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_200w.jpg",
"400w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_400w.jpg",
"600w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_600w.jpg",
"1000w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_1000w.jpg",
"64sq":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_64sq.jpg",
"200sq":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_200sq.jpg",
"400sq":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_400sq.jpg"
}
}
],
"variants":[
{
"variant":{
"id":14382188,
"name":"INDTTIN CD",
"position":1,
"sku":"",
"full_quantity":300,
"in_stock":300,
"percent_available":100,
"is_default_variant?":false,
"price":7.0,
"sold_out":false,
"status":"active"
}
}
],
"collections":[
],
"store":{
"id":373949,
"name":"On My Honor",
"marketplace_url":"http://www.storenvy.com/stores/373949-on-my-honor"
}
}
]
Here is my code:
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define storeURL [NSURL URLWithString: #"http://onmyhonor.storenvy.com/products.json"]
#import "GRSStoreViewController.h"
#import "GRSStoreDetailViewController.h"
#interface GRSStoreViewController ()
#end
#implementation GRSStoreViewController
#synthesize name, description, short_url, price, productImage, nameArray, descriptionArray, urlArray, priceArray, imageArray, url;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Store";
self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
url = [NSURL URLWithString:#"http://onmyhonor.storenvy.com/products.json"];
dispatch_async(kBgQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:url];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
nameArray = [[NSMutableArray alloc]init];
descriptionArray = [[NSMutableArray alloc]init];
urlArray = [[NSMutableArray alloc]init];
priceArray = [[NSMutableArray alloc]init];
imageArray = [[NSMutableArray alloc]init];
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
for (NSDictionary *item in json)
{
name = [item objectForKey:#"name"];
description = [item objectForKey:#"description"];
short_url = [item objectForKey:#"short_url"];
price = [item objectForKey:#"price"];
[nameArray addObject:name];
[descriptionArray addObject:description];
[urlArray addObject:short_url];
[priceArray addObject:price];
}
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [nameArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"Cell"];
cell.textLabel.font = [UIFont systemFontOfSize:16.0];
}
if (cell)
{
cell.textLabel.text = [nameArray objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor darkGrayColor];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
GRSStoreDetailViewController *itemDetail = [[GRSStoreDetailViewController alloc]initWithNibName:#"GRSStoreDetailViewController" bundle:nil];
itemDetail.priceString = [priceArray objectAtIndex:indexPath.row];
itemDetail.descriptionString = [descriptionArray objectAtIndex:indexPath.row];
itemDetail.itemURL = [urlArray objectAtIndex:indexPath.row];
[self.navigationController pushViewController:itemDetail animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Change loop to
for (NSDictionary *item in json)
{
NSArray *photos = item[#"photos"];
NSDictionary *dict = [photos[0] valueForKeyPath:"photo"];
NSLog(#"original = %#", dict[#"original"]);
name = [item objectForKey:#"name"];
description = [item objectForKey:#"description"];
short_url = [item objectForKey:#"short_url"];
price = [item objectForKey:#"price"];
[nameArray addObject:name];
[descriptionArray addObject:description];
[urlArray addObject:short_url];
[priceArray addObject:price];
}
Change this
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
for (NSDictionary *item in json)
{
name = [item objectForKey:#"name"];
description = [item objectForKey:#"description"];
short_url = [item objectForKey:#"short_url"];
price = [item objectForKey:#"price"];
[nameArray addObject:name];
[descriptionArray addObject:description];
[urlArray addObject:short_url];
[priceArray addObject:price];
}
[self.tableView reloadData];
To this
NSdictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
name = [json objectForKey:#"name"];
description = [json objectForKey:#"description"];
short_url = [json objectForKey:#"short_url"];
price = [json objectForKey:#"price"];
// this is your photos array
NSArray *photos = [josn objectForKey:#"photos"];
// every object in this array is a dictionary. In your case this array has only one dictionary so
NSDictionary *photosDict = [photos firstObject];
// from here you can access all keys of photosDict
All available keys in your photosDict:
original
large
homepage
medium
small
64w
200w
400w
600w
1000w
64sq
200sq
400sq
I am very new to Objective-C so please bear with me.
I have been working on a UIPickerView that uses JSON data and can change the values of the second component based on which option is selected on the first component.
I have used two examples I found online to try and create this, one for using JSON with a UIPickerView and one for a UIPickerView that changes the value of the second component based on the selection in the first.
I have got both of these examples working separately but can't combine them to get them to work.
I have a feeling I might be going about this the wrong way so I came here to get some help and advice.
Heres my code:
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *Nations;
NSMutableArray *England;
NSMutableArray *Espana;
NSMutableArray *Netherlands;
NSMutableArray *Germany;
NSMutableArray *Italy;
NSDictionary *Engdict;
NSDictionary *Espdict;
NSDictionary *Netdict;
NSDictionary *Gerdict;
NSDictionary *Itadict;
// Define keys
NSString *footballclub;
NSString *team;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Nations = [[NSMutableArray alloc]initWithObjects:#"England",#"Espana",#"Netherlands",#"Germany",#"Italy", nil];
footballclub = #"FootballClub";
England = [[NSMutableArray alloc] init];
Espana = [[NSMutableArray alloc] init];
Netherlands = [[NSMutableArray alloc] init];
Germany = [[NSMutableArray alloc] init];
Italy = [[NSMutableArray alloc] init];
NSData *EngjsonData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"http://url./England.php"]];
NSData *EspjsonData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"http://url.com/Espana.php"]];
NSData *NetjsonData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"http://url.com/Netherlands.php"]];
NSData *GerjsonData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"http://url.com/Germany.php"]];
NSData *ItajsonData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"http://url.com/Italy.php
id EngjsonObjects = [NSJSONSerialization JSONObjectWithData:EngjsonData options:NSJSONReadingMutableContainers error:nil];
id EspjsonObjects = [NSJSONSerialization JSONObjectWithData:EspjsonData options:NSJSONReadingMutableContainers error:nil];
id NetjsonObjects = [NSJSONSerialization JSONObjectWithData:NetjsonData options:NSJSONReadingMutableContainers error:nil];
id GerjsonObjects = [NSJSONSerialization JSONObjectWithData:GerjsonData options:NSJSONReadingMutableContainers error:nil];
id ItajsonObjects = [NSJSONSerialization JSONObjectWithData:ItajsonData options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *EngdataDict in EngjsonObjects) {
NSString *strFootballClub = [EngdataDict objectForKey:#"FootballClub"];
Engdict = [NSDictionary dictionaryWithObjectsAndKeys:
strFootballClub, footballclub,
nil];
[England addObject:Engdict];
}
for (NSDictionary *EspdataDict in EspjsonObjects) {
NSString *strFootballClub = [EspdataDict objectForKey:#"FootballClub"];
Espdict = [NSDictionary dictionaryWithObjectsAndKeys:
strFootballClub, footballclub,
nil];
[Espana addObject:Espdict];
}
for (NSDictionary *NetdataDict in NetjsonObjects) {
NSString *strFootballClub = [NetdataDict objectForKey:#"FootballClub"];
Netdict = [NSDictionary dictionaryWithObjectsAndKeys:
strFootballClub, footballclub,
nil];
[Netherlands addObject:Netdict];
}
for (NSDictionary *GerdataDict in GerjsonObjects) {
NSString *strFootballClub = [GerdataDict objectForKey:#"FootballClub"];
Gerdict = [NSDictionary dictionaryWithObjectsAndKeys:
strFootballClub, footballclub,
nil];
[Germany addObject:Gerdict];
}
for (NSDictionary *ItadataDict in ItajsonObjects) {
NSString *strFootballClub = [ItadataDict objectForKey:#"FootballClub"];
Itadict = [NSDictionary dictionaryWithObjectsAndKeys:
strFootballClub, footballclub,
nil];
[Italy addObject:Itadict];
}
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component
{
if(component ==0)
{
return [Nations count];
}
else {
if ([team isEqualToString:#"England"]) {
return [England count];
}
if ([team isEqualToString:#"Espana"]) {
return [Espana count];
}
if ([team isEqualToString:#"Netherlands"]) {
return [Netherlands count];
}
if ([team isEqualToString:#"Germany"]) {
return [Germany count];
}
else {
return [Italy count];
}
}
return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSDictionary *EngtmpDict = [England objectAtIndex:row];
NSDictionary *EsptmpDict = [Espana objectAtIndex:row];
NSDictionary *NettmpDict = [Netherlands objectAtIndex:row];
NSDictionary *GertmpDict = [Germany objectAtIndex:row];
NSDictionary *ItatmpDict = [Italy objectAtIndex:row];
if(component ==0)
{
return [Nations objectAtIndex:row];
}
else {
if ([team isEqualToString:#"England"]) {
return [EngtmpDict objectForKey:footballclub];
}
if ([team isEqualToString:#"Espana"]) {
return [EsptmpDict objectForKey:footballclub];
}
if ([team isEqualToString:#"Netherlands"]) {
return [NettmpDict objectForKey:footballclub];
}
if ([team isEqualToString:#"Germany"]) {
return [GertmpDict objectForKey:footballclub];
}
else {
return [ItatmpDict objectForKey:footballclub];
}
}
return 0;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == 0) {
team=[[NSString alloc] initWithFormat:#"%#" , [Nations objectAtIndex:row]];
[pickerView reloadComponent:1];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
}
#end
This comes up in the debug screen when I try to run it.
Terminating app due to uncaught exception 'NSRangeException',
reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
I am trying to get a JSON to iOS app, but keep getting NULL values..
- (id)initWithDictionary:(NSDictionary *)dictionary {
self.name = [dictionary valueForKey:#"name"];
self.amount = [NSString stringWithFormat:#"%#",
[dictionary valueForKey:#"amount"]];
self.goalId = [dictionary valueForKey:#"id"];
self.createdAt = [dictionary valueForKey:#"created_at"];
self.updatedAt = [dictionary valueForKey:#"updated_at"];
return self;
}
+ (NSArray *)findAllRemote {
NSURL *url = [NSURL URLWithString:#"http://localhost:3000/goals.json"];
NSError *error = nil;
NSString *jsonString =
[NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
NSLog(#"my string = %#", jsonString);
NSMutableArray *goals = [NSMutableArray array];
if (jsonString) {
SBJSON *json = [[SBJSON alloc] init];
NSArray *results = [json objectWithString:jsonString error:&error];
[json release];
for (NSDictionary *dictionary in results) {
Goal *goal = [[Goal alloc] initWithDictionary:dictionary];
[goals addObject:goal];
[goal release];
}
}
return goals;
}
JSON string looks correct:
my string = [{"goal":{"amount":"100.0","created_at":"2011-08-20T00:55:34Z","id":1,"name":"User","updated_at":"2011-08-20T00:55:34Z"}},{"goal":{"amount":"200.0","created_at":"2011-08-20T00:56:48Z","id":2,"name":"User2","updated_at":"2011-08-20T00:56:48Z"}},{"goal":{"amount":"19999.0","created_at":"2011-08-20T19:15:10Z","id":3,"name":"This is MY GOAL","updated_at":"2011-08-20T19:15:10Z"}},{"goal":{"amount":"0.0","created_at":"2011-08-20T20:46:44Z","id":4,"name":"goal","updated_at":"2011-08-20T20:46:44Z"}}]
I am missing something basic I guess..
UPDATE:
Here is a line that returns NULL (from another class):
- (IBAction)refresh {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
self.goals = [Goal findAllRemote];
[self.tableView reloadData];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Goals";
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refresh)];
self.navigationItem.rightBarButtonItem = refreshButton;
[refreshButton release];
[self refresh];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"GoalCellId";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
reuseIdentifier:CellIdentifier] autorelease];
}
Goal *goal = [goals objectAtIndex:indexPath.row];
cell.textLabel.text = goal.name;
cell.detailTextLabel.text = goal.amount;
return cell;
}
goal.name and goal.amount are Null..
This may not be part of your issue, but you should be calling [self init] (or more importantly, [super init] via inheritance):
- (id)initWithDictionary:(NSDictionary *)dictionary {
if (self = [self init]) {
self.name = [dictionary valueForKey:#"name"];
self.amount = [NSString stringWithFormat:#"%#",
[dictionary valueForKey:#"amount"]];
self.goalId = [dictionary valueForKey:#"id"];
self.createdAt = [dictionary valueForKey:#"created_at"];
self.updatedAt = [dictionary valueForKey:#"updated_at"];
}
return self;
}
Also:
for (NSDictionary *dictionary in results) {
Goal *goal = [[Goal alloc] initWithDictionary:
[dictionary objectForKey:#"goal"]];
[goals addObject:goal];
[goal release];
}
Key change is [dictionary objectForKey:#"goal"] in line 3.
The JSON array is of objects with a single goal member, with the properties that your initWithDictionary method is looking for.