Sort NSMutableArray that is value of NSMutableDictionary - ios

I have NSMutableDictionary with several keys (NSDate is the key) and value of each key is NSMutableArray whose objects are dictionaries. Each of this dictionary has NSDate "event_start_date" based on which I want to sort NSMutableArray. How can I achieve it? Here's the format of NSMutableDictionary that I've.
{
"2015-03-23 18:30:00 +0000" = (
{
"establishment_id" = 8;
"event_end_date" = "2015-03-24 20:15:00";
"event_image" = "";
"event_name" = "Event One";
"event_start_date" = "2015-03-24 19:15:00";
miles = "0.17";
"user_rate" = 0;
}
);
"2015-03-24 18:30:00 +0000" = (
{
"establishment_id" = 8;
"event_end_date" = "2015-03-25 20:20:00";
"event_image" = "";
"event_name" = "Second Event";
"event_start_date" = "2015-03-25 19:20:00";
miles = "0.17";
"user_rate" = 0;
},
{
"establishment_id" = 8;
"event_end_date" = "2015-03-30 01:00:00";
"event_image" = "";
"event_name" = getevent;
"event_start_date" = "2015-03-25 01:00:00";
miles = "0.17";
"user_rate" = 0;
},
{
"establishment_id" = 8;
"event_end_date" = "2015-03-25 15:40:00";
"event_image" = "";
"event_name" = "TestAdd Event with note";
"event_start_date" = "2015-03-25 14:40:00";
miles = "0.17";
"user_rate" = 0;
}
);
"2015-03-26 18:30:00 +0000" = (
{
"establishment_id" = 8;
"event_end_date" = "2015-03-27 11:25:00";
"event_image" = "http://venyounightout.com/images/1_2015_03_26_23_00_00.png";
"event_name" = "Perfect event";
"event_start_date" = "2015-03-27 10:25:00";
miles = "0.17";
"user_rate" = 0;
}
);
}

you may not sort an NSDictionary - you may sort an array you get from the dictionary however.
// get all keys into array
NSArray * keys = [your_dictionary allKeys];
// sort it
NSArray * sorted_keys = [keys sortedArrayUsingSelector:#selector(compare:)];
// now, access the values in order
for (NSDate * key in sorted_keys)
{
// get value
NSMutableString * your_value = [your_dictionary valueForKey: key];
// perform operations
}

You can sort an individual NSMutableArray of dictionaries by the "event_start_date" key using:
[array sortUsingDescriptors:#[ [NSSortDescriptor sortDescriptorWithKey:#"event_start_date" ascending:YES] ]];
To apply this to every value in a dictionary, you can do:
[dict enumerateKeysAndObjectsUsingBlock:^(id key, NSMutableArray* array, BOOL *stop){
[array sortUsingDescriptors:#[ [NSSortDescriptor sortDescriptorWithKey:#"event_start_date" ascending:YES] ]];
}];

Related

objective c how to get the specific json key value in ios

I have json response for all over country related json. My problem is I want to get the Algeria.png based on id key name and with out using icon name key. Anybody please guide me. And I want to get the image name dynamically not statically. I am using objective c code.
json for country array is:(
{
"dial_code" = "+93";
"icon_name" = "Afghanistan.png";
id = 1;
name = Afghanistan;
},
{
"dial_code" = "+355";
"icon_name" = "Albania.png";
id = 2;
name = Albania;
},
{
"dial_code" = "+213";
"icon_name" = "Algeria.png";
id = 3;
name = Algeria;
},
{
"dial_code" = "+1684";
"icon_name" = "American-Samoa.png";
id = 4;
name = "American Samoa";
},
{
"dial_code" = "+376";
"icon_name" = "Andorra.png";
id = 5;
name = Andorra;
},
{
"dial_code" = "+244";
"icon_name" = "Angola.png";
id = 6;
name = Angola;
},
You had array(this is JsonArray) of dictionaries. So
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"id == %#",[NSNumber numberWithInteger:3]];
(OR)
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"id == %#",3];
NSArray *tempArray = [JsonArray filteredArrayUsingPredicate:predicate];
In tempArray you will get dictionary object.
NSDcitionary *dict = [tempArray objectAtIndex:0];
NSString *imageName = [dict valueForKey:#"icon_name"];

Group and sum values of NSDictionary by month where key is NSDate

I have a dictionary with the following structure,
arrayOne = {
"2015-11-09T00:00:00.000Z" = 1;
"2015-11-16T00:00:00.000Z" = 2;
"2015-11-23T00:00:00.000Z" = 3;
"2015-11-30T00:00:00.000Z" = 4;
"2015-12-07T00:00:00.000Z" = 5;
"2015-12-14T00:00:00.000Z" = 6;
"2015-12-21T00:00:00.000Z" = 7;
"2015-12-28T00:00:00.000Z" = 8;
"2016-01-04T00:00:00.000Z" = 9;
"2016-01-11T00:00:00.000Z" = 1;
"2016-01-18T00:00:00.000Z" = 2;
"2016-01-25T00:00:00.000Z" = 3;
}
I'd like to create another dictionary with values like,
arrayTWo = {
"November" = 10;
"December" = 26;
"January" = 15;
}
I tried by getting month values of dates in a separate array and values in a separate array and then tried to get those in a nsmutabledictionary, but it does not assign value for duplicate keys and got a solution like
arrayTWo = {
"November" = 4;
"December" = 8;
"January" = 3;
}
I couldn't find a better way, Any options are appreciated. Thanks.
Try this, it uses NSDateFormatter to get the month name from the date, it's localized depending on the current locale. If your locale is not english and you need to get the english month names uncomment the line to set the locale explicitly.
The logic is simple:
Enumerate the dictionary, If the key (month) exists, add the value, if it doesn't create the key
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"MMMM";
// formatter.locale = [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSDate *key in arrayOne.allKeys) {
NSString *month = [formatter stringFromDate:key];
if (result[month] == nil) {
result[month] = arrayOne[key];
} else {
NSInteger value = [result[month] integerValue];
result[month] = #(value + [arrayOne[key] integerValue]);
}
}
NSLog(#"%#", result);

Q - iOS - Search and use specific part of parsed JSON array

This is my first time using JSON. In my app I am fetching some data from "Open Weather API". I get back some array, with way to many entries, and I need to search ones that are on specific day and return temp.day and weather.icon from them. So far I managed to fetch data propely. As far I know i should use some FOR loop with IF inside it, but I am pulling my hairs out how to do it in Objective C.
There is my fetch method:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* weatherList = [json objectForKey:#"list"];
NSLog(#"everything %#", weatherList ); //3
}
And part array from NSLog:
{
clouds = 92;
deg = 265;
dt = 1456221600;
humidity = 100;
pressure = "1007.96";
rain = "0.24";
speed = "5.12";
temp = {
day = "4.11";
eve = "4.62";
max = "4.87";
min = "2.78";
morn = "4.11";
night = "2.78";
};
weather = (
{
description = "light rain";
icon = 10d;
id = 500;
main = Rain;
}
);
},
{
clouds = 88;
deg = 268;
dt = 1456308000;
humidity = 98;
pressure = "1012.04";
rain = "1.31";
speed = "6.35";
temp = {
day = "3.57";
eve = "3.74";
max = "3.74";
min = "2.38";
morn = "2.53";
night = "2.38";
};
weather = (
{
description = "light rain";
icon = 10d;
id = 500;
main = Rain;
}
);
},
{
clouds = 20;
deg = 243;
dt = 1456394400;
humidity = 100;
pressure = "1015.42";
snow = "0.25";
speed = "5.08";
temp = {
day = "2.95";
eve = "4.09";
max = "4.54";
min = "-0.65";
morn = "1.74";
night = "-0.65";
};
weather = (
{
description = "light snow";
icon = 13d;
id = 600;
main = Snow;
}
);
},
{
clouds = 80;
deg = 273;
dt = 1456480800;
humidity = 100;
pressure = "1016.63";
snow = "0.04";
speed = "2.79";
temp = {
day = "0.2";
eve = "2.79";
max = "2.79";
min = "-3.33";
morn = "-2.7";
night = "-2.42";
};
weather = (
{
description = "light snow";
icon = 13d;
id = 600;
main = Snow;
}
);
},
{
clouds = 87;
deg = 132;
dt = 1456567200;
humidity = 0;
pressure = "1007.07";
rain = "0.22";
snow = "0.03";
speed = 5;
temp = {
day = "3.96";
eve = "1.48";
max = "3.96";
min = "-3.12";
morn = "-3.12";
night = "-1.59";
};
weather = (
{
description = "clear sky";
icon = 01d;
id = 800;
main = Clear;
}
);
}
What are good practices? Do I fetch proper enough big part of JSON?
Should I use dome NSDictionary too? Any ideas are welcome!
Thanks
1) As per documentation given the time is in GMT format so you need to convert the time in IST to compare
here is code to convert the time . I dont know your time zone I converted it in Indian Standard Time
for ( NSDictionary *obj in weatherList) {
NSDateFormatter *inDateFormatter = [[NSDateFormatter alloc] init];
inDateFormatter.dateFormat = #"dd-MM-yyyy";
inDateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"IST"];
NSDate *inDate = [inDateFormatter dateFromString:[obj objectForKey:#"dt"]];
if ([self isItToday:inDate]) {
NSDictionary * tempDict = [obj objectForKey:#"temp"];
NSDictionary * weatherDict = [[obj objectForKey:#"weather"]objectForKey:0];
NSString * dayTemp = [tempDict objectForKey:#"day"];//only storing for time being you can use where you needed
NSString * icon = [weatherDict objectForKey:#"icon"];//only storing for time being you can use where you needed
}
}
2) Now you need to compare it with todays date
+ (BOOL)isItToday:(NSDate *)date {
if (date != nil) {
NSString *givenDateString = [self stringFromDate:date inDateFormat:#"dd-MM-yyyy"];
NSString *toDayString = [self stringFromDate:[NSDate date] inDateFormat:#"dd-MM-yyyy"];
NSDate *givenDate = [self dateFromString:givenDateString inDateFormat:#"dd-MM-yyyy"];
NSDate *toDay = [self dateFromString:toDayString inDateFormat:#"dd-MM-yyyy"];
if ([givenDate isEqualToDate:toDay]) {
return YES;
} else {
return NO;
}
} else {
return NO;
}
}
+ (NSString *)stringFromDate:(NSDate *)date inDateFormat:(NSString *)inDateformat
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:kLocaleIdentifierEN_US_POSIX];
[dateFormatter setDateFormat:inDateformat];//#"dd/MM/yyyy"
return [dateFormatter stringFromDate:date];
}
+ (NSDate *)dateFromString:(NSString *)stringDate inDateFormat:(NSString *)inDateformat
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:kLocaleIdentifierEN_US_POSIX];
[dateFormatter setDateFormat:inDateformat];//#"dd/MM/yyyy"
return [dateFormatter dateFromString:stringDate];
}
also add this line
#define kLocaleIdentifierEN_US_POSIX [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"]
Use following code,
double comparingdt = 1456308000;
__block NSString *tempday, *weathericon;
[weatherList enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSDictionary *weather, NSUInteger idx, BOOL * _Nonnull stop) {
*stop = ([weather[#"dt"] doubleValue] == comparingdt);
if (*stop)
{
tempday = weather[#"temp"][#"day"];
weathericon = [weather[#"weather"] firstObject][#"icon"];
}
}];

How to get Date Value from array?

I want to store the date in a separate array…..How to do this???Am getting confused….Pls help me….
(
{
"2015-03-27" = {
amount = 13086;
date = "2015-03-26 18:30:00 +0000";
"date-day" = 27;
"date-month" = Mar;
"date-year" = 2015;
units = 2160;
};
},
{
"2015-08-03" = {
amount = 18300;
date = "2015-08-02 18:30:00 +0000";
"date-day" = 03;
"date-month" = Aug;
"date-year" = 2015;
units = 2950;
};
},
)
Your data is in Array (which is collection of Dictionary)
So, first get Dictionary from Array & then add key of particular dictionary in to new Array (which is resulted array of Dates)
Try this:
NSArray *arrData;
NSMutableArray *arrDates = [NSMutableArray array];
for (NSDictionary *dict in arrData) {
[arrDates addObject:[[dict allKeys] firstObject]];
}
NSLog(#"Dates :: %#", arrDates);
The outer object is an array, item 0 contains the two dictionaries.
NSDictionary *dictionary = array[0];
Then enumerate the dictionary and extract the date values
NSMutableArray *dates = [NSMutableArray array];
for (NSString *key in dictionary) {
[dates addObject: dictionary[key][#"date"]];
}

How to merge 2 NSDictionaries in NSMutableArray having same value in iOS?

I have an NSMutableArray with NSDictionaries like below format
(
{
"login_id" = 95;
consDays = "Mon,Tue";
consEndTime = 12600000;
consStartTime = 9000000;
duration = 10;
id = 58;
isActive = 1;
},
{
"login_id" = 95;
consDays = "Wed,Thur";
consEndTime = 41400000;
consStartTime = 23400000;
duration = 10;
id = 59;
isActive = 1;
},
{
"login_id" = 98;
consDays = "Mon,Tue,Wed,Thur,Fri,Sat,Sun";
consEndTime = 45000000;
consStartTime = 9000000;
duration = 30;
id = 60;
isActive = 1;
},
I can see here first 2 object's with "login_id" 95 are same and i need to merge the contents and make something like this one
{
"login_id" = 95;
consDays = "Mon,Tue-Wed,Thur";
consEndTime = 12600000-41400000;
consStartTime = 9000000-23400000;
duration = 10;
id = 58;
isActive = 1;
},
i have tried with for loop and its not getting clear
for(int i=0;i<[[arr valueForKey:#"data"] count];i++){
NSString *bloginId=[NSString stringWithFormat:#"%#",[[[arr valueForKey:#"data"] valueForKey:#"branchLogin_id"] objectAtIndex:i]];
for(int j=0;j<[[arr valueForKey:#"data"] count];j++){
NSString *firstId=[NSString stringWithFormat:#"%#",[[[arr valueForKey:#"data"] valueForKey:#"branchLogin_id"] objectAtIndex:i]];
NSString *secondId=[NSString stringWithFormat:#"%#",[[[arr valueForKey:#"data"] valueForKey:#"branchLogin_id"] objectAtIndex:j]];
NSLog(#"%#-%#",firstId,secondId);
if([firstId isEqualToString:secondId]){
NSLog(#"%#",[consultationDetailsArray valueForKey:#"branchLogin_id"]);
if([[consultationDetailsArray valueForKey:#"branchLogin_id"] containsObject:secondId]){
NSString *str=[NSString stringWithFormat:#"%#,%#",[[consultationDetailsArray valueForKey:#"consDays"] objectAtIndex:j],[[[arr valueForKey:#"data"] valueForKey:#"consDays"] objectAtIndex:j]];
NSLog(#"consDays %#",str);
}else{
[consultationDetailsArray addObject:[[arr valueForKey:#"data"] objectAtIndex:j]];
}
}
}
}
can anyone help me ?
Ironically I am doing just this same thing right now. Looks like the easiest way is to use a NSMutableDictionary.
// Assume two starting dictionaries.
dictionaryOne;
dictionaryTwo;
//
// Create a mutable copy of the first
NSMutableDictionary *merged = dictionaryOne.mutableCopy;
[merged addEntriesFromDictionary: dictionaryTwo];
//
// merged now contains all keys of both dictionaries
// keys that are in both dictionaries will have values
// from dictionaryTwo.
Hope this helps.

Resources