how to make a new NSDictionary from a NSDictionary where key = x - ios

i have a app that gets some json data from a mysql server via a web api like this:
[[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:#"streamGames", #"command", nil] onCompletion:^(NSDictionary *json) {
//got stream
[[API sharedInstance] setGames:[json objectForKey:#"result"]];
this gives me :
{
awayScor = 3;
data = "2014-04-11";
gameType = 1;
homeScor = 2;
homeTeam = "Herning Blue Fox";
time = "21:00";
},
{
awayScor = 1;
data = "2014-04-08";
gameType = 2;
homeScor = 2;
homeTeam = "SønderjyskE";
time = "19:00";
},
now what i want to do i make a new NSDictionary where i only add data where lets say gameType = 1 so i have a new NSDictionary for etch gameType.

If I've understood the question correctly!
NSArray *games; // Get this from somewhere
NSMutableDictionary *gameTypes = [NSMutableDictionary dictionary];
for (NSDictionary *game in games) {
NSNumber *gameType = game[#"gameType"];
NSMutableArray *gamesForType = gameTypes[gameType];
if (!gamesForType) {
gamesForType = [NSMutableArray array];
gameTypes[gameType] = gamesForType;
}
[gamesForType addObject:game];
}
Now gameTypes will be a dictionary of game types to an array games of that type.

Related

how to store data in object and that object store in array in ios

How can I store these three dictionaries in an object and those three objects store in an array? how can I retrive this data from array?
[
{
"gender_desc" = Male;
"gender_id" = 1;
"gender_isactive" = 1;
},
{
"gender_desc" = Female;
"gender_id" = 2;
"gender_isactive" = 1;
},
{
"gender_desc" = Other;
"gender_id" = 3;
"gender_isactive" = 1;
}
]
Using this,
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
you can parse your json data into dictionaries.
First of all this json structure is wrong. Json should be like :
{
"gender_detail":[
{
"gender_desc" = Male;
"gender_id" = 1;
"gender_isactive" = 1;
},
{
"gender_desc" = Female;
"gender_id" = 2;
"gender_isactive" = 1;
},
{
"gender_desc" = Other;
"gender_id" = 3;
"gender_isactive" = 1;
}
]
}
Then create a mutable array and store these values :
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
[dataArray addObjectsFromArray:[dictionary valueForKey:#"gender_details"]];
After this array is ready.
Now suppose you want gender_desc value of first object.
NSString *gender_desc = [[dataArray objectAtIndex:0] valueForKey:#"gender_desc"];
Do likewise for other details.
So you want to parse JSON into NSDictionaries, NSArrays and the like? The are many libraries that will happily accommodate this task, or Apple's docs can help you roll your own. Looking on SO, here just one place to start, Convert JSON feed to NSDictionary

Downloading calendar data in Objective-C

I am trying to download google calendar data.
I am following a tutorial this link according to which implementing some of the GoogleOAuth delegate methods will let me get my desired data.
First I converted the response JSON data into an NSDictionary object and after that, I, NSLog this dictionary, to see the way the returned data is formed which is as shown below.
calendarInfoDict is {
etag = "\"1436255371893000\"";
items = (
{
accessRole = owner;
backgroundColor = "#9a9cff";
colorId = 17;
defaultReminders = (
{
method = popup;
minutes = 30;
}
);
etag = "\"1436255371893000\"";
foregroundColor = "#000000";
id = "sabiranthapa#gmail.com";
kind = "calendar#calendarListEntry";
notificationSettings = {
notifications = (
{
method = email;
type = eventCreation;
},
{
method = email;
type = eventChange;
},
{
method = email;
type = eventCancellation;
},
{
method = email;
type = eventResponse;
}
);
};
primary = 1;
selected = 1;
summary = "sabiranthapa#gmail.com";
timeZone = "Asia/Calcutta";
},
{
accessRole = reader;
backgroundColor = "#92e1c0";
colorId = 13;
defaultReminders = (
);
description = "Displays birthdays of people in Google Contacts and optionally \"Your Circles\" from Google+. Also displays anniversary and other event dates from Google Contacts, if applicable.";
etag = "\"1436255358367000\"";
foregroundColor = "#000000";
id = "#contacts#group.v.calendar.google.com";
kind = "calendar#calendarListEntry";
summary = Birthdays;
timeZone = "Asia/Calcutta";
}
);
kind = "calendar#calendarList";
nextSyncToken = 00001436255371893000;
}
According to tutorial there is a block containing a bunch of information regarding every calendar I have created in Google Calendars inside curly bracket. But I am not getting any events that I have saved which can be seen in Google Calendar after signing in gmail but not in my apps where I need to work with it.
My code is
-(void)responseFromServiceWasReceived:(NSString *)responseJSONAsString andResponseJSONAsData:(NSData *)responseJSONAsData{
NSError *error;
if ([responseJSONAsString rangeOfString:#"calendarList"].location != NSNotFound) {
NSDictionary *calendarInfoDict = [NSJSONSerialization JSONObjectWithData:responseJSONAsData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"calendarInfoDict is %#", calendarInfoDict);
if (error) {
NSLog(#"%#", [error localizedDescription]);
}
else{
NSArray *calendarsInfo = [calendarInfoDict objectForKey:#"items"];
if (_arrGoogleCalendars == nil) {
_arrGoogleCalendars = [[NSMutableArray alloc] init];
}
for (int i=0; i<[calendarsInfo count]; i++) {
NSDictionary *currentCalDict = [calendarsInfo objectAtIndex:i];
NSArray *values = [NSArray arrayWithObjects:[currentCalDict objectForKey:#"id"],
[currentCalDict objectForKey:#"summary"],
nil]; NSArray *keys = [NSArray arrayWithObjects:#"id", #"summary", nil];
[_arrGoogleCalendars addObject:
[[NSMutableDictionary alloc] initWithObjects:values forKeys:keys]];
}
_dictCurrentCalendar = [[NSDictionary alloc] initWithDictionary:[_arrGoogleCalendars objectAtIndex:0]];
[_barItemPost setEnabled:YES];
[_barItemRevokeAccess setEnabled:YES];
[self showOrHideActivityIndicatorView];
But I always end up with condition
if (_arrGoogleCalendars == nil) {
_arrGoogleCalendars = [[NSMutableArray alloc] init];
}
without able to access my events.
How can I download (or access) my Events from google calendar?

How to replace the value of the key in NSMutableDictionary based on the another key value pair

I have one NSArray with NSMutableDictionaries .Example testArray =[dict1,dict2,dict3,dict4].
Each dictionary in the array is something like
dict1= {
country = "INDIA";
flag = "A";
Currency = "Rupees";
rate = 10;
}
The all values are changeable. Sometimes
dict1 = {
country = "USA";
flag = "SA";
Currency = "Dollar";
rate = 50;
}
I need to update the value of the key rate of all dictionaries in the testArray if country = "INDIA" and flag = "A" and Currency = "Rupees" and Do not need to change the value of the rate key all other dictionaries in side the testArray.
Just try the below.
for(NSMutableDictionary *dic in array)
{
if([[dic valueForKey:#"country"] isEqualToString:#"INDIA"] &&
[[dic valueForKey:#"flag"] isEqualToString:#"A"] &&
[[dic valueForKey:#"Currency"] isEqualToString:#"Rupees"])
{
[dic setValue:#"100" forKey:#"rate"];
}
}
Here is a complete example what you need
NSDictionary *dict1 = #{
#"country" : #"INDIA",
#"flag" : #"A",
#"Currency" : #"Rupees",
#"rate" : #10
};
NSDictionary *dict2 = #{
#"country" : #"USA",
#"flag" : #"SA",
#"Currency" : #"Dollar",
#"rate" : #50
};
NSArray *testArray = #[dict1, dict2];
NSMutableArray *testMutableArray = [testArray mutableCopy];
for (int i = 0; i < testMutableArray.count; i++) {
NSDictionary *country = testMutableArray[i];
if ([country[#"country"] isEqualToString:#"INDIA"] &&
[country[#"flag"] isEqualToString:#"A"] &&
[country[#"Currency"] isEqualToString:#"Rupees"])
{
NSMutableDictionary *countryMutable = [country mutableCopy];
countryMutable[#"rate"] = #100;
testMutableArray[i] = [countryMutable copy];
}
}
testArray = [testMutableArray copy];
Use NSMutableArray instead of NSArray.
then,
NSDictionary *dict = [testArray objectAtIndex:0];
dict[#"rate"] = #"11";
[testArray replaceObjectAtIndex:0 withObject:dict];
Hope this will help you.

how to group array of nsdictionary according to the value inside the element

I have array of dictionary that needs to be grouped according to PO which is part of the element and also get the total of quantityOrdered according to the same PO.
The PO is dynamic it means it can be any value that needs to be filtered and compute the quantityOrderd accordingly.
Please help.
{
PO = PO2;
QuantityReceived = 1;
},
{
PO = PO1;
QuantityReceived = 3;
},
{
PO = PO1;
QuantityReceived = 3;
},
{
PO = PO3;
QuantityReceived = 2;
},
{
PO = PO2;
QuantityReceived = 2;
},
{
PO = PO3;
QuantityReceived = 4;
},
{
PO = PO1;
QuantityReceived = 1;
},
Apology for the confusion or incomplete question but i need to create a new array of dictionary with similar like this :
{
PO = PO1;
TotalQuanityReceived=7;
LineItems=3;
},
{
PO = PO2;
TotalQuanityReceived=3;
LineItems=2;
},
{
PO = PO3;
TotalQuanityReceived=6;
LineItems=2;
},
i updated my example and make it easy to read.
- (NSArray *)whatever:(NSArray *)dictionaries
{
NSMutableArray *results = [[NSMutableArray alloc] init];
NSMutableDictionary *resultsByPO = [[NSMutableDictionary alloc] init];
for (NSDictionary *dictionary in dictionaries) {
id po = [dictionary objectForKey:#"PO"];
NSMutableDictionary *result = [resultsByPO objectForKey:po];
if (result == nil) {
result = [[NSMutableDictionary alloc] init];
[resultsByPO setObject:result forKey:po];
[results addObject:result];
[result setObject:po forKey:#"PO"];
}
double total = [[result objectForKey:#"TotalQuantityReceived"] doubleValue];
total += [[dictionary objectForKey:#"QuantityOrdered"] doubleValue];
int count = 1 + [[result objectForKey:#"Count"] intValue];
[result setObject:#(total) forKey:#"TotalQuantityReceived"];
[result setObject:#(count) forKey:#"Count"];
}
return results;
}
More pain will come with PO values not conforming to NSCopying.
You can do it the clever way with KVC or the stupid easy way. Let's do it the stupid easy way!
Make an empty NSMutableDictionary. Let's call it dict.
Cycle through your array of dictionaries. For each dictionary:
Fetch its PO. Call that value thisPO.
Fetch dict[thisPO]. Was it nil?
a. Yes. Okay, so this particular PO has not yet been encountered. Set dict[thisPO] to this dictionary's quantity received (as an NSNumber).
b. No. Turn that value into an integer, add this dictionary's quantity received, and set the total back into dict[thisPO] (as an NSNumber).
Done! The result is not quite what you asked for; the result looks like this:
{
PO1 = 100;
PO2 = 120;
...
}
But now, you see, the work of totalling is done and it is easy to transform that into an array of dictionaries if that is what you want.
Not 100% sure if this is what you are saying or not, but to sort an array of dictionaries based on one of the elements it would look something like this.
NSDictionary *d1 = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithDouble:100],#"PO",
[NSNumber numberWithDouble:0], #"Category",
nil];
NSDictionary *d2 = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithDouble:50],#"PO",
[NSNumber numberWithDouble:90], #"Category",
nil];
NSArray *unsorted = #[d1, d2];
NSArray *sortedArray;
sortedArray = [unsorted sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSDictionary *first = (NSDictionary*)a;
NSDictionary *second = (NSDictionary*)b;
NSNumber *firstPO = [first objectForKey:#"PO"];
NSNumber *secondPO = [second objectForKey:#"PO"];
return [firstPO compare:secondPO];
}];
NSLog(#"unsorted = %#", unsorted);
NSLog(#"sorted = %#", sortedArray);
I wasn't really sure what PO was, so I just used an NSNumber as an example. Look at this page for an overview of how you would compare a customer object. http://nshipster.com/nssortdescriptor/.
Then you can loop through the array, now in the correct order and build your next NSDictionary.

Accessing the xml values from NSDictionary

I am using this xmlreader. Here is my code
NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:&error1];
NSLog(#"XMLData: %#",xmlDict);
I can save and log the data and it looks like this.
response = {
Gpn0 = {
text = 10000;
};
Gsn0 = {
text = 4;
};
btn0 = {
text = up;
};
};
}
But how can I access a single element from this dictionary?
NSDictionary *gpn0 = response[#"Gpn0"];
NSNumber *gpn0_text = gpno[#"text"]; // note this is a numeric value
NSDictionary *btn0 = response[#"btn0"];
NSString *btn0_text = gpno[#"text"]; // note this is a string value
so on and so forth

Resources