Multidimensional array issues - iphone

I am creating a multidimensional array for sections / rows based on json data from our API. Looking at the logs the adding rows and sections look good but when I nslog the sections it only shows a bunch of the last object. It seems like the rows are not being added to sections.
What am I doing wrong to make the last API object show in the sections x times? x represents the json count. self.appointments is an NSArray *
According to objective-c multi-dimensional array it should work.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableArray *sections = [[NSMutableArray alloc] init];
NSMutableArray *rows = [[NSMutableArray alloc] init];
NSString *lastDate = nil;
for (NSDictionary *dict in [json objectForKey:#"data"]) {
NSString *date = [dict objectForKey:#"date"];
NSLog(#"Dates: %# - %#", date, lastDate);
if (date != lastDate) {
if (lastDate == nil) {
NSLog(#"Adding Row 1");
[rows addObject:dict];
lastDate = date;
} else {
NSLog(#"Adding Section 1");
NSLog(#"Adding #rows %i",[rows count]);
[sections addObject:rows];
[rows removeAllObjects];
NSLog(#"Adding Row 2 %#",[dict objectForKey:#"start_time"]);
[rows addObject:dict];
lastDate = date;
}
} else {
NSLog(#"Adding Row 3");
[rows addObject:dict];
}
}
if (rows) {
NSLog(#"Adding Section 2");
NSLog(#"Adding #rows %i",[rows count]);
[sections addObject:rows];
}
NSLog(#"Sections: %#", sections);
self.appointments = [sections mutableCopy]; //I have also tried self.appointments = sections
sections = nil;
rows = nil;
Logs show
Sections: (
(
{
abbrev = "";
account = "";
"addOnService_id" = "";
alert = "";
"appt_id" = 1839384;
"appt_id_unique" = 1839384;
"appt_status_description" = "";
"appt_status_type" = "";
"c_id" = 47;
cost = "0.00";
"coupon_id" = "";
"creation_emp_id" = 2288;
"creation_timestamp" = 201111040717;
"customer_id" = 0;
"customer_notes" = "";
"customer_package_id" = "";
date = 20121228;
"employee_id" = 2288;
"employee_notes" = "";
employer = "";
"end_time" = 570;
"first_name" = "";
"history_id" = 1830959;
key = 134;
"last_emp_id" = 2288;
"last_name" = "";
"last_timestamp" = 201111040717;
"lead_description" = "";
"link_id" = 0;
"location_name" = "Telephonic Setup/Training";
"make_id" = "";
"middle_name" = "";
"model_id" = "";
"model_year" = "";
name = "My Name ";
odometer = "";
"other_vehicle" = "";
"package_name" = "";
"payment_type_description" = "";
"payment_type_id" = "";
"pet_id" = "";
"po_number" = "";
reason = "B.O.B";
"rebook_id" = "";
"recur_id" = 20954;
"rep_id" = "";
"room_id" = 0;
"room_name" = "";
service = "";
"service_id" = 0;
"service_time_description" = "";
spots = 1;
"staff_screen_name" = "John Smith";
"staff_type_id" = 0;
"start_time" = 540;
"status_id" = 0;
tip = "";
"type_id" = 8;
vin = "";
}
),
(
{
abbrev = "";
account = "";
"addOnService_id" = "";
alert = "";
"appt_id" = 1839384;
"appt_id_unique" = 1839384;
"appt_status_description" = "";
"appt_status_type" = "";
"c_id" = 47;
cost = "0.00";
"coupon_id" = "";
"creation_emp_id" = 2288;
"creation_timestamp" = 201111040717;
"customer_id" = 0;
"customer_notes" = "";
"customer_package_id" = "";
date = 20121228;
"employee_id" = 2288;
"employee_notes" = "";
employer = "";
"end_time" = 570;
"first_name" = "";
"history_id" = 1830959;
key = 134;
"last_emp_id" = 2288;
"last_name" = "";
"last_timestamp" = 201111040717;
"lead_description" = "";
"link_id" = 0;
"location_name" = "Telephonic Setup/Training";
"make_id" = "";
"middle_name" = "";
"model_id" = "";
"model_year" = "";
name = "My Name ";
odometer = "";
"other_vehicle" = "";
"package_name" = "";
"payment_type_description" = "";
"payment_type_id" = "";
"pet_id" = "";
"po_number" = "";
reason = "B.O.B";
"rebook_id" = "";
"recur_id" = 20954;
"rep_id" = "";
"room_id" = 0;
"room_name" = "";
service = "";
"service_id" = 0;
"service_time_description" = "";
spots = 1;
"staff_screen_name" = "John Smith";
"staff_type_id" = 0;
"start_time" = 540;
"status_id" = 0;
tip = "";
"type_id" = 8;
vin = "";
}
), ... over and over again.

With:
[sections addObject:rows];
[rows removeAllObjects];
[rows addObject:dict];
you keep adding the same rows object not a new one and keep changing the contents so the last contents display each time.
Try:
[sections addObject:[rows mutableCopy]];
[rows removeAllObjects];
[rows addObject:dict];
That way a new row is added each time.
Perhaps better yet:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableArray *sections = [NSMutableArray array];
NSMutableArray *rows = [NSMutableArray array];
NSString *lastDate = nil;
for (NSDictionary *dict in [json objectForKey:#"data"]) {
NSString *date = [dict objectForKey:#"date"];
if ([date isEqualToString:lastDate] == NO) {
if (lastDate == nil) {
[rows addObject:dict];
lastDate = date;
} else {
[sections addObject:rows];
rows = [NSMutableArray array];
[rows addObject:dict];
lastDate = date;
}
[rows addObject:dict];
}
}
if (rows) {
[sections addObject:rows];
}
self.appointments = sections;
Note that assigning 0 to an object does not release it, release does. But if you use convenience methods to create objects then they are autoreleased and no further action is necessary to release them.
Also note that when comparing strings one needs to use the isEqualToString: method to compare the contents, just using the = or != only compares the address of the strings.

Related

How to filter array of NSDictionary for key separated by comma

I have an array of NSDictionary.NSDictionary has a key named as multiple_image key that contain string separated by ,.
I want set of array that contain 123.png for multiple_images key.
Can some one show me how to do this using NSPredicate or without predicate.
//Array
{
Image = "<UIImage: 0xf72df30>";
active = yes;
"admin_id" = 169;
"category_id" = 32;
"chef_id" = 175;
descr = "Cool tea to cool down the mind.";
id = 110;
"multiple_images" = "Jellyfish.jpg,345.png";
name = "Southern Sweet Ice Tea";
price = 160;
rating = 3;
selected = 0;
"subcat_id" = 23;
"tag_id" = 45;
"tax_id" = 10;
"tax_value" = "12.00";
},
{
Image = "<UIImage: 0xf72ebd0>";
active = yes;
"admin_id" = 169;
"category_id" = 31;
"chef_id" = 175;
descr = "Ingredients are almonds or cashews. No hydrogenated stuff, no extra weirdo ingredients";
id = 107;
"multiple_images" = "Jellyfish.jpg,123.png";
name = "Butter Chicken";
price = 300;
rating = 3;
selected = 0;
"subcat_id" = 24;
"tag_id" = 43;
"tax_id" = 9;
"tax_value" = "0.00";
},
{
Image = "<UIImage: 0xf72f870>";
active = yes;
"admin_id" = 169;
"category_id" = 31;
"chef_id" = 173;
descr = "Raw vegetables including carrots, cucumbers.";
id = 100;
"multiple_images" = "Jellyfish.jpg,shake.png,";
name = Salads;
price = 50;
rating = 3;
selected = 0;
"subcat_id" = 22;
"tag_id" = 44;
"tax_id" = 9;
"tax_value" = "0.00";
}
Using predicates,
[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"multiple_images CONTAINS '123'"]];
Using predicates, but with blocks
NSArray *filtered = [test filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:
^BOOL(NSDictionary *evaluatedObject, NSDictionary * bindings) {
NSString *key = #"123";
return ([evaluatedObject[#"multiple_images"] rangeOfString:key].location != NSNotFound);
}]];
Try
NSDictionary *item = mainArray[0];
NSString *imagesString = item[#"multiple_images"];
NSArray *images = [imagesString componentsSeparatedByString:#","];
Now you can use the images
Try this code
for (int i=0; i<[mainArray count]; i++) {
NSDictionary *item = [mainArray objectAtIndex:i];
NSString *imagesString = item[#"multiple_images"];
NSArray *images = [imagesString componentsSeparatedByString:#","];
for (int j=0;j<[images count]; j++) {
if ([[images objectAtIndex:j] isEqualToString:#"123.png"]) {
///Your Required code;
}
}
}
So you want to save the dictionary that has 123.png.
maybe you can try something like this:
NSMutableArray *arr = [NSMutableArray new];// your array of objects(dictionaries)
__block NSMutableArray *images123 = [NSMutableArray new];
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSMutableDictionary *dictionary = (NSMutableDictionary *)obj;
if([[dictionary allKeys]containsObject:#"multiple_images"]){
NSString *imageList = (NSString *)[dictionary objectForKey:#"multiple_images"];
NSArray *arrayImages = [imageList componentsSeparatedByString:#","];
if([arrayImages containsObject:#"123.png"]){
[images123 addObject:dictionary];
}
}
}];

Sorting array of multiple dictionaries

My array contains three dictionaries per object of the array.
{
avg = {
avg1 = 50;
avg2 = 60;
};
posts = {
alcoholContent = 450;
name = "BBB";
origin = United States;
};
reviews = {
rev1 = "Test review 1";
rev2 = "Test review 2";
};
}
{
avg = {
avg1 = 30;
avg2 = 20;
};
posts = {
alcoholContent = 550;
name = "AAA";
origin = United States;
};
reviews = {
rev1 = "Test review 1";
rev2 = "Test review 2";
};
}
I want to sort array acceding by key "name" (of post dictionary).
How can I do it?
I tried normal sorting methods using sort descriptors, but did not work
Try sortUsingComparator:
[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDictionary *dict1 = obj1;
NSDictionary *dict2 = obj2;
NSString *string1 = [[dict1 objectForKey:#"posts"] objectForKey:#"name"];
NSString *string2 = [[dict2 objectForKey:#"posts"] objectForKey:#"name"];
return [string1 compare:string2];
}];

how to select image from JSON parsed in Array

I am using JSON parsing, I put data in array named JSON Array. In console it looks like
JSON Array=(
{
"created_by" = 42;
"created_on" = "2012-02-29 11:23:37";
"file_description" = "";
"file_is_downloadable" = 0;
"file_is_forSale" = 0;
"file_is_product_image" = 1;
"file_meta" = "";
"file_mimetype" = "image/jpeg";
"file_params" = "";
"file_title" = "hand shovel";
"file_type" = product;
"file_url" = "images/stories/virtuemart/product/cca3cd5db813ee6badf6a3598832f2fc.jpg";
"file_url_thumb" = "images/stories/virtuemart/product/resized/cca3cd5db813ee6badf6a3598832f2fc_90x90.jpg";
"locked_by" = 0;
"locked_on" = "0000-00-00 00:00:00";
"modified_by" = 42;
"modified_on" = "2012-02-29 11:23:37";
ordering = 0;
"product_name" = "Hand Shovel";
published = 0;
shared = 0;
"virtuemart_category_id" = 1;
"virtuemart_media_id" = 13;
"virtuemart_product_id" = 1;
"virtuemart_vendor_id" = 1;
},
{
"created_by" = 42;
"created_on" = "2012-02-29 11:35:09";
"file_description" = "";
"file_is_downloadable" = 0;
"file_is_forSale" = 0;
"file_is_product_image" = 1;
"file_meta" = "";
"file_mimetype" = "image/jpeg";
"file_params" = "";
"file_title" = "our ladder";
"file_type" = product;
"file_url" = "images/stories/virtuemart/product/8cb8d644ef299639b7eab25829d13dbc.jpg";
"file_url_thumb" = "images/stories/virtuemart/product/resized/8cb8d644ef299639b7eab25829d13dbc_90x90.jpg";
"locked_by" = 0;
"locked_on" = "0000-00-00 00:00:00";
"modified_by" = 42;
"modified_on" = "2012-02-29 11:35:09";
ordering = 0;
"product_name" = Ladder;
published = 0;
shared = 0;
"virtuemart_category_id" = 3;
"virtuemart_media_id" = 8;
"virtuemart_product_id" = 2;
"virtuemart_vendor_id" = 1;
},
Now from this i need to select "file_url_thumb" which is actually image in seperate array.
please let me know how can i do this?
//Your array has two dictionary ..
for(NSMutableDictionary *dict in JSON_Array){
NSString *urlString = [dict objectForKey:#"file_url_thumb"];
if(urlString){
NSURL *url = [NSURL urlWithString:urlString];
NSData* imageData = [[NSData alloc] initWithContentsOfURL:url]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
//show your image on imageview
}
}
Hope this will help you
NSString *str_URL =[ [json objectAtIndex:anIndex] valueForKey:#"file_url_thumb"];
NSString *urlString = [[jsonArray objectAtIndex:0] objectForKey:#"file_url_thumb"];
This will give you value for "file_url_thumb" as a string.

convert dictionary to array after removing key values

i need to remove first three keys values from each index of array. What i did is
for (int i=0; i<[normalscoringarray count]; i++)
{
NSDictionary *dictionary = [normalscoringarray objectAtIndex:i];
NSMutableDictionary *mutableDictionary = [dictionary mutableCopy];
[mutableDictionary removeObjectForKey:#"cn"];
[mutableDictionary removeObjectForKey:#"gdate"];
[mutableDictionary removeObjectForKey:#"gid"];
NSLog(#"mutableDictionary.....%#",mutableDictionary);
NSMutableArray *remainingArray = [[NSMutableArray alloc]init];
for (id item in mutableDictionary) {
[remainingArray setArray:[mutableDictionary objectForKey:item]];
}
}
and it does not give remainingArray in that order i want, more over it removes all keys.
normalscoringarray....(
{
cn = "Ranjit Garh";
gdate = "2012-03-25";
gid = 1;
id = 1;
p1nets = "3,3,4,4,2,2,2,4,3,3,4,2,5,3,5,4,3,4||27||33||60";
p1nh = "BP||14||1";
p1score = "4,4,5,5,3,3,3,5,4,4,5,3,5,3,6,4,4,5||36||39||75||61";
p1spoints = "3,3,3,2,3,4,3,3,3,3,2,4,1,2,2,1,3,3||27||21||48";
p2nets = "4,3,4,4,3,4,2,5,4,4,3,3,4,3,6,3,4,4||33||34||67";
p2nh = "DG||18||2";
p2score = "5,4,5,5,4,5,3,6,5,5,4,4,5,4,7,4,5,5||42||43||85||67";
p2spoints = "2,3,3,2,2,2,3,2,2,2,3,3,2,2,1,2,2,3||21||20||41";
p3nets = "4,3,6,4,2,3,2,4,5,4,3,5,6,3,4,3,5,6||33||39||72";
p3nh = "NM||24||3";
p3score = "6,5,7,6,4,5,3,6,6,5,5,6,7,4,5,4,6,7||48||49||97||73";
p3spoints = "2,3,1,2,3,3,3,3,1,2,3,1,0,2,3,2,1,1||21||15||36";
p4nets = "3,4,5,4,2,3,3,5,3,4,3,5,4,3,5,3,4,6||32||37||69";
p4nh = "KS||20||4";
p4score = "5,5,6,5,3,5,4,6,4,5,5,6,5,4,6,4,5,7||43||47||90||70";
p4spoints = "3,2,2,2,3,3,2,2,3,2,3,1,2,2,2,2,2,1||22||17||39";
},
{
cn = "Eden Garden";
gdate = "2012-03-26";
gid = 2;
id = 2;
p1nets = "3,2,5,3,1,2,2,4,4,3,4,3,5,2,5,3,3,5||26||33||59";
p1nh = "NM||24||3";
p1score = "5,4,6,5,3,4,3,6,5,4,5,4,6,3,6,4,4,6||41||42||83||59";
p1spoints = "3,4,2,3,4,4,3,3,2,3,2,3,1,3,2,2,3,2||28||21||49";
p2nets = "2,4,5,3,2,4,3,4,4,4,3,3,5,2,5,3,4,4||31||33||64";
p2nh = "KS||20||4";
p2score = "4,5,6,4,3,6,4,5,5,5,4,4,6,3,6,4,5,5||42||42||84||64";
p2spoints = "4,2,2,3,3,2,2,3,2,2,3,3,1,3,2,2,2,3||23||21||44";
p3nets = "3,4,5,5,3,5,4,5,5,5,4,5,5,4,5,3,5,6||39||42||81";
p3nh = "AK||18||5";
p3score = "4,5,6,6,4,6,5,6,6,6,5,6,6,5,6,4,6,7||48||51||99||81";
p3spoints = "3,2,2,1,2,1,1,2,1,1,2,1,1,1,2,2,1,1||15||12||27";
p4nets = "2,4,5,4,3,3,3,5,5,4,3,5,4,3,5,4,5,6||34||39||73";
p4nh = "KR||20||6";
p4score = "4,5,6,5,4,5,4,6,6,5,4,6,5,4,6,5,6,7||45||48||93||73";
p4spoints = "4,2,2,2,2,3,2,2,1,2,3,1,2,2,2,1,1,1||20||15||35";
},
)
the way i want
normalscoringarray....(
id = 1,
p1nets = "3,3,4,4,2,2,2,4,3,3,4,2,5,3,5,4,3,4||27||33||60",
p1nh = "BP||14||1",
p1score = "4,4,5,5,3,3,3,5,4,4,5,3,5,3,6,4,4,5||36||39||75||61",
p1spoints = "3,3,3,2,3,4,3,3,3,3,2,4,1,2,2,1,3,3||27||21||48",
p2nets = "4,3,4,4,3,4,2,5,4,4,3,3,4,3,6,3,4,4||33||34||67",
p2nh = "DG||18||2",
p2score = "5,4,5,5,4,5,3,6,5,5,4,4,5,4,7,4,5,5||42||43||85||67",
p2spoints = "2,3,3,2,2,2,3,2,2,2,3,3,2,2,1,2,2,3||21||20||41",
p3nets = "4,3,6,4,2,3,2,4,5,4,3,5,6,3,4,3,5,6||33||39||72",
p3nh = "NM||24||3",
p3score = "6,5,7,6,4,5,3,6,6,5,5,6,7,4,5,4,6,7||48||49||97||73",
p3spoints = "2,3,1,2,3,3,3,3,1,2,3,1,0,2,3,2,1,1||21||15||36",
p4nets = "3,4,5,4,2,3,3,5,3,4,3,5,4,3,5,3,4,6||32||37||69";
p4nh = "KS||20||4";
p4score = "5,5,6,5,3,5,4,6,4,5,5,6,5,4,6,4,5,7||43||47||90||70",
p4spoints = "3,2,2,2,3,3,2,2,3,2,3,1,2,2,2,2,2,1||22||17||39",
)
NSMutableArray *remainingArray = [[NSMutableArray alloc]init];
for (int i=0; i<[normalscoringarray count]; i++)
{
NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] initWithDictionary:[normalscoringarray objectAtIndex:i]]; //each time alloc and init with contents of normalscoringarray
//Remove values for keys
[mutableDictionary removeObjectForKey:#"cn"];
[mutableDictionary removeObjectForKey:#"gdate"];
[mutableDictionary removeObjectForKey:#"gid"];
[remainingArray addObject:mutableDictionary]; //add mutableDictionary to remainingArray
[mutableDictionary release]; //free mutableDictionary
}
//finally print contents of remainingArray
NSLog(#"normalscoringarray:\n%#",[remainingArray description]);
Hope this would be help you!
for (int i=0; i<[normalscoringarray count]; i++)
{
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithDictionary:[normalscoringarray objectAtIndex:i]];
[dictionary removeObjectForKey:#"cn"];
[dictionary removeObjectForKey:#"gdate"];
[dictionary removeObjectForKey:#"gid"];
[normalscoringarray replaceObjectAtIndex:i withObject:dictionary];
}

Loop through NSDictionary to create separate NSArrays

I have a large NSDictionary that I need to loop through and create separate NSArrays. Here are the contents:
(
{
id = {
text = "";
};
sub = {
text = " , ";
};
text = "";
"thumb_url" = {
text = "";
};
title = {
text = "2010-2011";
};
type = {
text = "title";
};
},
{
id = {
text = "76773";
};
sub = {
text = "December 13, 2010";
};
text = "";
"thumb_url" = {
text = "http://www.puc.edu/__data/assets/image/0004/76774/varieties/thumb.jpg";
};
title = {
text = "College Days - Fall 2010";
};
type = {
text = "gallery";
};
},
{
id = {
text = "";
};
sub = {
text = "";
};
text = "";
"thumb_url" = {
text = "";
};
title = {
text = "2009-2010";
};
type = {
text = "title";
};
},
{
id = {
text = "76302";
};
sub = {
text = "December 3, 2010";
};
text = "";
"thumb_url" = {
text = "http://www.puc.edu/__data/assets/image/0019/76303/varieties/thumb.jpg";
};
title = {
text = "Christmas Colloquy";
};
type = {
text = "gallery";
};
}
)
Each section has a type key, which I need to check. When it finds the title key, I need to add those to an array. Then the next sections that would use the gallery key needs to be in its own array until it finds another title key. Then the gallery keys after that into their own array.
I am using a UITableView section titles and content. So, the NSDictionary above should have one NSArray *titles; array, and two other arrays each containing the galleries that came after the title.
I have tried using a for loop but I just can't seem to get it right. Any ideas would be appreciated.
It's somewhat unclear by your log, but I'm guessing your NSDictionary has values of NSDictionary? If so:
NSMutableArray *titles = [NSMutableArray array];
// etc.
for (id key in sourceDictionary) {
NSDictionary *subDictionary = [sourceDictionary objectForKey:key];
if ([subDictionary objectForKey:#"type"] == #"title")
[titles addObject:[subDictionary objectForKey:#"title"]];
// etc.
}
Your question is a bit unclear... but this is how you would properly loop through an NSDictionary.
EDIT:
NSMutableDictionary *galleries = [NSMutableDictionary dictionary];
NSString *currentTitle;
for (id key in sourceDictionary) {
NSDictionary *subDictionary = [sourceDictionary objectForKey:key];
NSString *type = [subDictionary objectForKey:#"type"];
if (type == #"title") {
currentTitle = [subDictionary objectForKey:#"title"];
if ([galleries objectForKey:currentTitle] == nil)
[galleries setObject:[NSMutableArray array] forKey:currentTitle];
} else if (type == #"gallery" && currentTitle != nil)
[[galleries objectForKey:currentTitle] addObject:subDictionary];
}
After this loop, galleries will contain keys of type NSString (with values of the titles), and corresponding objects of type NSArray (with values of the gallery NSDictionarys). Hopefully this is what you were going for.
NSString *key;
for(key in someDictionary){
NSLog(#"Key: %#, Value %#", key, [someDictionary objectForKey: key]);
}
Modern Objective-C syntax:
NSMutableArray *things = [NSMutableArray array];
NSMutableArray *stuff = [NSMutableArray array];
NSMutableArray *bits = [NSMutableArray array];
[dictionaries enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[things addObject:[obj valueForKeyPath:#"thing"]];
[stuff addObject:[obj valueForKeyPath:#"enclosing_object.stuff"]];
[bits addObject:[obj valueForKeyPath:#"bits"]];
}];