I have a JSON request getting this:
bills = (
{
id = 1;
name = "Cursus Nibh Venenatis";
value = "875.24";
},
{
id = 2;
name = "Elit Fusce";
value = "254.02";
}
);
I'm creating a NSDictionary for it.
I'm using JSONKit and I wanna know how can I populate my UITableView with this values? Thanks for any help!
EDIT
NSLog(#"my dictionary = %#", resultsDictionary);
my dictionary = {
bills = (
{
id = 1;
name = "Cursus Nibh Venenatis";
value = "875.24";
},
{
id = 2;
name = "Elit Fusce";
value = "254.02";
}
);
}
It looks like your bills dictionary is composed of an array of smaller dictionaries. You'd access it like this;
get the top Dictionary bills.
access each dictionary inside (for loop, etc) and create an array
load table view data from previously created array
Edit*
NSDictionary *billsDictionary = [NSDictionary dictionaryWithDictionary:[resultsDictionary objectForKey:bills]];
NSMutableArray *dataSource = [[NSMutableArray alloc]init]; //make this an ivar and your tabelView's data source.
for(NSDictionary *dict in billsDictionary){
[dataSource addObject:dict];
}
[tableView reloadData];
//then in your tableView cell
cell.textLabel.text = [[NSString stringWithFormat:#"%#", [[dataSource objectAtIndex:indexPath.row]objectForKey:#"name"]]
//Repeat for whatever else you want to add to the cell (subtitle, image, etc.) Hope this helps.
It seems like In the result dictionary, you are having an Array. Where each object in your Array is a dictionary. Tryout the following code.
NSArray *billsArray = [resultsDictionary objectForKey:#"bills"];
give [[billsArray objectAtIndex:indexPath.row] objectForKey:#"name"] in your tableView datasource method tableView: cellForRowAtIndexPath:
Related
I have a pList looking like this when i log it:
{
Hans = {
Highscore = 0;
Name = Hans;
};
},
{
joe = {
Highscore = 0;
Name = joe;
};
},
{
Iben = {
Highscore = 0;
Name = Iben;
};
},
{
Erik = {
Highscore = 0;
Name = Erik;
};
}
I would really like to make these values in my pList into objects of Players when ViewDidLoad is called. Im not sure how to do so thought. Can somebody maybe help?
Load the plist into an array (appears you already have this but still I added this step)
NSString *path = [[NSBundle mainBundle] pathForResource:#"PlayerData" //Filename
ofType:#"plist"];
NSArray *loadedArray = [[NSArray alloc] initWithContentsOfFile:path];
Create an empty mutable array to store your player instances:
NSMutableArray *playersArray = [[NSMutableArray alloc] init];
Loop through your loaded array, creating Player instances and adding them to your mutable array
for (NSDictionary *dictionary in loadedArray) {
Player *player = [[Player alloc] init];
player.name = dictionary[#"Name"];
player.highscore = dictionary[#"Highscore"];
[playersArray addObject:player];
}
Note: Ideally you want a initialiser method in your player, like this:
- (instancetype)initWithName:(NSString *)name highscore:(NSNumber *)highscore;
I have an array of items, each with their own unique descriptions. Basically, I want to create a method which takes each item from the array and returns a single descriptive string which shows the description of each item in said array.
- (NSString *) itemList
{
NSString *list = [[NSString alloc] init];
for (Item *i in _items)
{
/**
Unsure :S
*/
[NSString stringWithFormat:#"%#: %#.\n", [i firstId], [i name]];
}
return list;
}
Basically, this is the coded logic that I have so far.
Assume I have two items which are initialised as such:
Item *testItem1 = [[Item alloc] initWithIdentifiers:#[#"shovel", #"spade"] name:#"a shovel" andDesc:#"This is a mighty fine shovel"];
Item *testItem2 = [[Item alloc] initWithIdentifiers:#[#"gem", #"crystal"] name:#"a gem" andDesc:#"This is a shiny gem"];
I then add those items to my Inventory object:
[testInventory put:testItem1];
[testInventory put:testItem2];
By calling the Inventory method itemList
[testInventory itemList];
on my inventory (code listed above), I want the following result:
#"shovel: a shovel.\ngem a gem."
Does anyone have any suggestions or pointers. I'm sure it's simple; it's just that I've only recently picked up Obj - C :)
Thanks
You can just use:
list = [list stringByAppendingFormat:#"%#: %#\n", [i firstId], [i name]];
or try NSMutableString:
NSMutableString *list = [[NSMutableString alloc] init];
[list appendFormat:#"%#: %#\n", [i firstId], [i name]];
You can do it more elegantly by overriding the description method for your Item class like this:
- (NSString *) description {
return [NSString stringWithFormat:"%#: %#.", [self firstId], [self name]];
}
and then to generate the string for all the items in the array:
NSString* itemsString = [itemList componentsJoinedByString:#"\n"];
I like adding the collection of strings to a mutable array and then calling componentsJoinedByString. It works even more cleanly if it is the description method you want on each object because you don't have to do the collecting loop first.
Create nsmutablearray
For each item in list
Nsmutablearray add object item.property
Return nsmutablearray componentsJoinedByString #", "
If you want the item's description though, you can just do, assuming you have an array with the objects already
TheArray componentsJoinedByString #", "
I created an NSArray from a CoreData fetch like so:
self.farSiman = [self.managedObjectContext executeFetchRequest:request error:&error];
In a tableview I used this code to get my custom objects:
Holiday *holiday = [self.dates objectAtIndex:indexPath.row];
cell.nameLabel.text = holiday.name;
But Im now in another viewcontroller, trying to plot the data on a mapkit, so in the plotting method i originally did this because i was getting an array from a plist file. But now my array is of custom Holiday objects so this doesnt work anymore:
NSLog(#"dictionary is %#", self.farSiman);
for (NSDictionary * dict in self.farSiman) {
NSNumber * latitude = [dict objectForKey:#"latitude"];
NSNumber * longitude = [dict objectForKey:#"longitude"];
NSString * storeDescription = [dict objectForKey:#"name"];
NSString * address = [dict objectForKey:#"address"];
NSLog(#"logging location %#", storeDescription);
CLLocationCoordinate2D coordinate;
coordinate.latitude = latitude.doubleValue;
coordinate.longitude = longitude.doubleValue;
MyLocation *annotation = [[MyLocation alloc] initWithName:storeDescription address:address coordinate:coordinate];
[_mapView addAnnotation:annotation];
}
My dictionary log prints out this:
dictionary is (
"<Holiday: 0x838bc80> (entity: Holiday; id: 0x838ca60 <x-coredata://E41B0CCD-2F03-4C4F-B054-18537096771C/Holiday/p1> ; data: <fault>)",
"<Holiday: 0x838e330> (entity: Holiday; id: 0x838ca70 <x-coredata://E41B0CCD-2F03-4C4F-B054-18537096771C/Holiday/p2> ; data: <fault>)"
Which means its an array of holiday objects.
How do I get each object in my for loop since Im using enumeration instead of a traditional for i = 0; i<count; i++?
It looks like you are using a custom object with CoreData, so it will be returning an array of your class.
Does this work:
for (Holiday *holiday in self.farSiman) {
// your code here
// [holiday foo]
}
If CoreData is not using your custom object, it will return an array of NSManagedObject, in which case use this:
for (NSManagedObject *holiday in self.farSiman) {
// your code here
//[holiday valueForKey:#"foo"]
}
Can't handle simple problem - adding cells to UITableView.
I have single-view application, with added from Objects - Table View and simple NSArray (deseriliazed json from internet-grabbed data).
- (void) didLoadMusicList:(APIDownload *)request
{
NSLog(#"Music list loaded");
CJSONDeserializer *deserializer = [CJSONDeserializer new];
NSDictionary *dict = [deserializer deserializeAsDictionary:request.downloadData error:nil];
NSArray *response = [dict objectForKey:#"response"];
NSArray *audios = [response subarrayWithRange:NSMakeRange(1, response.count-1)];
for(int i = 0; i < audios.count; i++)
{
NSDictionary *audio = [audios objectAtIndex:i];
// add a cell?
}
}
So, how do I add cell for each element?
You need to implement the UITableViewDatasource on your view controller. You can use the same array to provide the data to the cells, and return them using the cellForRowAtIndexPath datasource method. You also need to provide with the count of cells on your tableView.
Check this documentation: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewDataSource_Protocol/Reference/Reference.html
I'm trying to parse a very simple json object with 1 value. (ocUnit test below)
- (void) testHatCartParseWithValidRefId {
NSString* data = #"{\"refid\":999}";
Cart* obj = [HatCartParseJson parseJsonAndReturnObject:data];
STAssertTrue([obj.refid isEqualToString:#"999"], #"fail");
}
In the implementation everything fails when I add the line to pull it from either key or index. How should I pull this from the json input? Please keep in mind I need this json parse (not string) the actual code I'm working with is a large set of JSON data.
+ (Cart *) parseJsonAndReturnObject:(NSString *)json
{
NSArray* cart = [json JSONValue];
for (NSDictionary* item in cart) {
Cart* obj = [[Cart alloc] init];
//NSString* refid = [item objectAtIndex:0];
//NSString* refid = [item objectForKey:#"refid"];
[obj setRefid:#"999"];
return obj;
}
return nil;
}
Thank you in advance
You are expecting that the return value of JSONValue is an NSArray, which in this case it isn't.
So, you must do a check if the return value is actually an NSArray, and if it is, then iterate through the collection, otherwise check if it's an NSDictionary, and if it is, then return the Cart object with the refid from the NSDictionary. If all of this fails, then just return nil.
As a side point, according to Apple's Object Ownership Policy, you should return autorelease-d objects from methods whose names do not contain the words "alloc", "new" or "copy". This would be one such method where you'd return an autorelease-d object.
+ (Cart *) parseJsonAndReturnObject:(NSString *)json
{
id cart = [json JSONValue];
NSString* refid = nil;
if([cart isKindOfClass:[NSArray class]]) {
refid = [[cart objectAtIndex:0] objectForKey:#"refid"];
} else if([cart isKindOfClass:[NSDictionary class]]) {
refid = [cart objectForKey:#"refid"];
}
if(refid) {
Cart* c = [[Cart alloc] init];
[c setRefid:refid];
return [c autorelease];
}
return nil;
}